首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将SeekableByteChannel转换为FileChannel

将SeekableByteChannel转换为FileChannel
EN

Stack Overflow用户
提问于 2013-05-11 09:23:21
回答 1查看 784关注 0票数 1

直接来自 oracle教程:

下面的代码片段通过使用newByteChannel方法之一打开一个文件,用于读写。返回的SeekableByteChannel被转换为FileChannel。

这就是他们在上面提到的链接中所提到的片段。

代码语言:javascript
复制
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。我看不出这个过程。它是隐藏/运行在背景/或任何其他源魔法类的东西?提前谢谢。

EN

回答 1

Stack Overflow用户

发布于 2013-05-11 09:27:26

可以使用派生类(或接口)作为目标。因此,如果FileChannel.open()返回一个SeekableByteChannel,那么只要SeekableByteChannel是从FileChannel派生出来的,或者FileChannel是由SeekableByteChannel实现的接口,就可以使用分配给FileChannel (如您的示例中所示)的赋值。

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

澄清一下:当编译器不知道对象或无关对象时,我会使用“强制转换”一词。

也就是说,在C中,我可以将char *转换为int *,只要我知道自己在做什么,它就能工作。

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

代码语言:javascript
复制
Object a = new String();
String b = (String)a;

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16495647

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档