最近收到一条评论answer我应该远离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 ( FileInputStream
) 的情况下读取文件的 NIO 类?编辑:
Java 6(或仅之前)
最佳答案
Java 6 只有 FileInputStream.getChannel()
, FileOutputStream.getChannel()
, 和 RandomAccessFile.getChannel()
Java 7 有 java.nio.channels.FileChannel.open(...)
和 java.nio.Files.newByteChannel(...)
关于java - 在不使用 java.io.* 的情况下获取 FileChannel(使用纯 NIO),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2036921/