Java 随机读取文件 RandomAccessFile 基于字节 byte

更多 Java IO & NIO方面的文章,请参见文集《Java IO & NIO》


  • Instances of this class support both reading and writing to a random access file.
    支持对文件的随机访问及读写操作。
  • A random access file behaves like a large array of bytes stored in the file system. There is a kind of cursor, or index into the implied array, called the file pointer;
    有一个游标或者索引 file pointer,来访问字节数组
  • getFilePointer() 得到当前 file pointer
  • seek(long pos) 修改当前 file pointer

RandomAccessFile 的使用:

public static void main(String[] args) throws Exception {
    RandomAccessFile raf = new RandomAccessFile("r.txt", "rw");

    raf.writeUTF("你好");
    System.out.println(raf.getFilePointer());
    raf.seek(0);
    String s = raf.readUTF();
    System.out.println(s);
}

输出:

8
你好

你可能感兴趣的:(Java 随机读取文件 RandomAccessFile 基于字节 byte)