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

标签 java file-io copy nio channel

最近收到一条评论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/

相关文章:

php - 在 PHP 中复制大文件(超过 2 GB)

java - 如何使多个基于文本的 java 菜单工作?

java - 如何使用 JAXB 编码注释为 @XmlAttachmentRef 的 DataHandler?

java - Sonar 安装问题 : Unrecognized VM option '+HeapDumpOnOutOfMemoryError'

networking - 在两台相邻计算机之间传输文件的最快方法

c++ - 包含原子的类的 std::vector

通过远程访问找不到 java web start jar 文件

c - 如何用 C 语言读取和编辑 .txt 文件?

java - 如何在Java中检测USB驱动器

postgresql - Postgresql查询中的COPY命令