代码之家  ›  专栏  ›  技术社区  ›  user85421

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

  •  2
  • user85421  · 技术社区  · 16 年前

    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 或其他NIO类,用于在不使用java.io的情况下读取文件( FileInputStream

    编辑:
    Java 6(或之前版本)

    2 回复  |  直到 9 年前
        1
  •  6
  •   tangens    16 年前

    这个 javadoc of FileChannel 说:

    也就是说,使用Java1.6,您无法获得 FileChannel 不用旧的 java.io .

        2
  •  7
  •   Aleksandr Dubinsky    12 年前

    FileInputStream.getChannel() , FileOutputStream.getChannel() RandomAccessFile.getChannel()

    Java7已经 java.nio.channels.FileChannel.open(...) 和 java.nio.Files.newByteChannel(...)