gpt4 book ai didi

java - 将 SeekableByteChannel 转换为 FileChannel

转载 作者:太空宇宙 更新时间:2023-11-04 07:38:04 27 4
gpt4 key购买 nike

直接来自this oracle java教程:

The following code snippet opens a file for both reading and writing by using one of the newByteChannel methods. The SeekableByteChannel that is returned is cast to a 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。好吧,我没有看到这个过程。它是否隐藏/在后台运行/或任何其他来源魔法之类的东西?提前致谢。

最佳答案

您可以使用派生类(或接口(interface))作为目标。因此,如果 FileChannel.open() 返回 SeekableByteChannel,则可以使用对 FileChannel 的分配(如示例中所示),只要 SeekableByteChannel 派生自 FileChannel 或 FileChannel 是由 SeekableByteChannel 实现的接口(interface)。

在这种情况下我不会使用术语“cast”,因为这是隐式完成的。

只是为了澄清:当对象对编译器未知或不相关时,我会使用术语“强制转换”。

即在 C 中,我可以将 char * 转换为 int *,只要我知道我在做什么,它就可以工作。

在 Java 中,如果我有这样的代码:

Object a = new String();
String b = (String)a;

编译器不知道 a 是什么,我真的必须使用强制转换。如果编译器知道层次结构并且它对目标有效,则不需要指定强制转换,这就是上面示例中发生的情况。编译器知道这些类型并且它们是安全的。

关于java - 将 SeekableByteChannel 转换为 FileChannel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16495647/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com