Java File Channel

FileChannel is available as a part of Java NIO (New IO).Java NIO (New IO) is an alternative to the standard Java IO API's. Java NIO offers a different way of working with IO than the standard IO API's. File channels are safe for use by multiple concurrent threads. This article demonstrate with working example of how to write and read file using FileChannel.
Advantages of File Channels
  • File channels are safe for use by multiple concurrent threads.
  • Reading and writing at a specific position in a file.
  • transfer file data from one channel to another at a faster rate.
  • lock a section of a file to restrict access by other threads.

Example of Reading and Writing File

Following example demonstrate how to read and write file using FileChannel.
JavaFileChannelHelper
package bootng.com.files;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

public class JavaFileChannelHelper {
  
  public static void main(String[] args) {
    JavaFileChannelHelper example = new JavaFileChannelHelper();
    try {
      example.write("samplefile.txt","This is it");
      String content = example.read("samplefile.txt");
      System.out.println(content + "  " );
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  public String read(String source) throws IOException {
    StringBuilder content = new StringBuilder("");
    RandomAccessFile file = new RandomAccessFile(source, "r");
    FileChannel channel = file.getChannel();
    ByteBuffer buf = ByteBuffer.allocate(48);
    while (channel.read(buf) > 0) {
      content.append(new String(buf.array(), StandardCharsets.UTF_8 ));
    }
     System.out.println("Read success!");
    return content.toString();
  }
  
  public void write(String source, String content) throws IOException {
    RandomAccessFile file = new RandomAccessFile(source, "rw");
    FileChannel channel = file.getChannel();
    ByteBuffer buff = ByteBuffer.wrap(content.getBytes(StandardCharsets.UTF_8));
    channel.write(buff);
    System.out.println("Write success!");
      }
}
Notes
  • Channels read and write buffers containing the content.
  • Channels are bi directional, that is we can both write and read in a channel.