将SeekableByteChannel转换为FileChannel

时间:2013-05-11 09:23:22

标签: java io nio

直接来自this 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。 好吧,我没有看到这个过程。它是隐藏/运行在背景/或任何其他来源神奇的东西? 提前谢谢。

1 个答案:

答案 0 :(得分:1)

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

在这种情况下,我不会使用术语“强制转换”,因为这是隐式的。

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

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

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

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

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