2

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

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 和循环)

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

编辑:
Java 6(或仅之前)

4

2 回答 2

7

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

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

于 2013-12-18T16:27:53.460 回答
6

FileChannel的javadoc说:

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

也就是说,在 java 1.6 中,如果FileChannel不使用 old就无法获得 a java.io

于 2010-01-10T13:00:01.500 回答