随机存取 Files

随机访问文件允许非 Sequences 或随机访问文件的内容。要随机访问文件,请打开文件,查找特定位置,然后读取或写入该文件。

SeekableByteChannelinterface可以实现此功能。 SeekableByteChannelinterface以当前位置的概念扩展了通道 I/O。方法使您可以设置或查询位置,然后可以从该位置读取数据或将数据写入该位置。该 API 包含一些易于使用的方法:

使用通道 I/O 读写文件显示Path.newByteChannel方法返回SeekableByteChannel的实例。在默认文件系统上,您可以按原样使用该通道,也可以将其强制转换为FileChannel,从而可以使用更高级的功能,例如将文件的区域直接 Map 到内存中以加快访问速度,锁定文件的区域。文件,或从绝对位置读取和写入字节,而不会影响通道的当前位置。

以下代码段通过使用newByteChannel方法之一打开了一个用于读取和写入的文件。返回的SeekableByteChannel被强制转换为FileChannel。然后,从文件的开头读取 12 个字节,并 Importing 字符串“我在这里!”。写在那个位置。文件中的当前位置移到末尾,并从头开始添加 12 个字节。最后,字符串“我在这里!”被附加,并且文件上的通道被关闭。

String s = "I was here!\n";
byte data[] = s.getBytes();
ByteBuffer out = ByteBuffer.wrap(data);

ByteBuffer copy = ByteBuffer.allocate(12);

try (FileChannel fc = (FileChannel.open(file, READ, WRITE))) {
    // Read the first 12
    // bytes of the file.
    int nread;
    do {
        nread = fc.read(copy);
    } while (nread != -1 && copy.hasRemaining());

    // Write "I was here!" at the beginning of the file.
    fc.position(0);
    while (out.hasRemaining())
        fc.write(out);
    out.rewind();

    // Move to the end of the file.  Copy the first 12 bytes to
    // the end of the file.  Then write "I was here!" again.
    long length = fc.size();
    fc.position(length-1);
    copy.flip();
    while (copy.hasRemaining())
        fc.write(copy);
    while (out.hasRemaining())
        fc.write(out);
} catch (IOException x) {
    System.out.println("I/O Exception: " + x);
}