在不使用java.io. *的情况下获取FileChannel(使用纯NIO)

use*_*421 2 java file-io nio copy channel

最近,我对这个答案发表了评论,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();
}
Run Code Online (Sandbox Code Playgroud)

(代码极其简化:最终尝试删除并循环执行)

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

编辑:
Java 6(或之前)

tan*_*ens 5

FileChannelJavadoc说:

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

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


Ale*_*sky 5

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

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