直接来自这个oracle java 教程:
以下代码片段使用其中一种 newByteChannel 方法打开一个文件以供读取和写入。返回的 SeekableByteChannel 被强制转换为 FileChannel。
这是他们在我上面提到的同一个链接中谈论的片段。
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);
}
所以基本上他们在谈论 Files.newByteChannel() 方法,该方法返回一个 SeekableByteChannel 对象,该对象又被强制转换为 FileChannel。好吧,我没有看到这个过程。它是隐藏/在后台运行/或任何其他资源魔法之类的东西吗?提前致谢。