1

直接来自这个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。好吧,我没有看到这个过程。它是隐藏/在后台运行/或任何其他资源魔法之类的东西吗?提前致谢。

4

1 回答 1

1

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

不过,在这种情况下,我不会使用术语“演员”,因为这是隐含的。

澄清一下:当编译器不知道或不相关的对象时,我会使用术语“转换”。

CI 中的 iE 可以将 char * 转换为 int *,只要我知道自己在做什么,它就会起作用。

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

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

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

于 2013-05-11T09:27:26.727 回答