首页javanio_bufferJava I/O - 如何使用RandomAccessFile和MappedByteBuffer上下读取文件

Java I/O - 如何使用RandomAccessFile和MappedByteBuffer上下读取文件

我们想知道如何使用RandomAccessFile和MappedByteBuffer上下读取文件。
 


import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
  public static void main(String[] args) throws Exception {
    RandomAccessFile f = new RandomAccessFile("hello.txt", "rw");
    FileChannel fc = f.getChannel();
    MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, f.length());

    int len = (int) f.length();
    for (int i = 0, j = len - 1; i < j; i++, j--) {
      byte b = mbb.get(i);
      mbb.put(i, mbb.get(j));
      mbb.put(j, b);
    }
    fc.close();
  }
}