In this example you’ll see how to read data from buffer using FileChannel.write()
method call. Reading from a buffer means that you are writing data into the channel object. In the snippet below the data from our dummy buffer will be read and written into the result.txt
file.
package org.kodejava.io;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class BufferRead {
public static void main(String[] args) throws Exception {
FileChannel channel = null;
try {
// Define an output file and create an instance of FileOutputStream
File file = new File("result.txt");
FileOutputStream fos = new FileOutputStream(file);
// Create a dummy ByteBuffer which value to be read into a channel.
ByteBuffer buffer = ByteBuffer.allocate(256);
buffer.put(new byte[]{65, 66, 67, 68, 69, 70, 71, 72, 73, 74});
// Change the buffer from writing mode to reading mode.
buffer.flip();
// Gets the channel from the FileOutputStream object and read the
// data available in buffer using channel.write() method.
channel = fos.getChannel();
int bytesWritten = channel.write(buffer);
System.out.println("written : " + bytesWritten);
} finally {
if (channel != null && channel.isOpen()) {
channel.close();
}
}
}
}
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023