【问题标题】:get FileChannel without using java.io.* (use pure NIO)在不使用 java.io.* 的情况下获取 FileChannel(使用纯 NIO)
【发布时间】:2011-01-03 11:05:05
【问题描述】:

最近收到answer 的评论,如果我想使用“纯 NIO”,我应该远离java.io
这是简化的代码(复制一个文件):

private static void copy(File source, File destination) throws IOException {
    long length = source.length();
    FileChannel input = new FileInputStream(source).getChannel();
    FileChannel output = new FileOutputStream(destination).getChannel();

    input.transferTo(0, length, output);

    output.close();
    input.close();
}

(代码极其简化:删除了 try-finally 和循环)

我的问题是如何在不使用 java.io (FileInputStream) 的情况下获取 FileChannel 或其他 NIO 类来读取文件?

编辑:
Java 6(或之前的版本)

【问题讨论】:

    标签: java file-io copy nio channel


    【解决方案1】:

    Java 6 只有FileInputStream.getChannel()FileOutputStream.getChannel()RandomAccessFile.getChannel()

    Java 7 有 java.nio.channels.FileChannel.open(...)java.nio.Files.newByteChannel(...)

    【讨论】:

      【解决方案2】:

      javadoc of FileChannel 说:

      这个类没有定义打开现有文件或创建新文件的方法;这些方法可能会在未来的版本中添加。在此版本中,可以通过调用该对象的 getChannel 方法从现有的 FileInputStream、FileOutputStream 或 RandomAccessFile 对象获取文件通道,该方法返回连接到同一底层文件的文件通道。

      也就是说,在 java 1.6 中,如果不使用旧的 java.io,您将无法获得 FileChannel

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-24
        • 1970-01-01
        • 1970-01-01
        • 2023-04-07
        • 1970-01-01
        相关资源
        最近更新 更多