Java I/O How to - Save and read text using FileChannel with CharBuffer








Question

We would like to know how to save and read text using FileChannel with CharBuffer.

Answer

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/*from   w ww .  j  av  a2s.c  om*/
public class MainClass {

  public static void main(String[] args) throws Exception {
    FileChannel fc = new FileOutputStream("data2.txt").getChannel();
    ByteBuffer buff = ByteBuffer.allocate(24); // More than needed
    buff.asCharBuffer().put("Some text");
    fc.write(buff);
    fc.close();

    fc = new FileInputStream("data2.txt").getChannel();
    buff.clear();
    fc.read(buff);
    buff.flip();
    System.out.println(buff.asCharBuffer());

  }
}

The code above generates the following result.