随机存取 Files
随机访问文件允许非 Sequences 或随机访问文件的内容。要随机访问文件,请打开文件,查找特定位置,然后读取或写入该文件。
SeekableByteChannelinterface可以实现此功能。 SeekableByteChannel
interface以当前位置的概念扩展了通道 I/O。方法使您可以设置或查询位置,然后可以从该位置读取数据或将数据写入该位置。该 API 包含一些易于使用的方法:
-
position –返回通道的当前位置
-
position(long) –设置 Channels 的位置
-
read(ByteBuffer) –从通道读取字节到缓冲区
-
write(ByteBuffer) –将字节从缓冲区写入通道
-
truncate(long) –截断连接到通道的文件(或其他实体)
使用通道 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);
}