首页javanio_bufferJava I/O - 如何使用FileChannel和CharBuffer保存和读取文本

Java I/O - 如何使用FileChannel和CharBuffer保存和读取文本

我们想知道如何使用FileChannel和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());

  }
}