Mega Code Archive

 
Categories / Java Tutorial / File
 

Save and read text using FileChannel with CharBuffer

import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; 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());   } } /*  */ Some text