使用纯NIO获取FileChannel而不使用java.io.*

3

最近我在这个答案中收到了一条评论,说如果我想使用“纯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 (或之前版本)

2个回答

7

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

Java 7新增了java.nio.channels.FileChannel.open(...)java.nio.Files.newByteChannel(...)


6
“FileChannel”的javadoc中写道:

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

也就是说,在Java 1.6中,您无法使用新的“java.nio”获取“FileChannel”,而必须使用旧的“java.io”。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接