2010-01-10 27 views
2

最近我对answer发表了评论,如果我想使用“纯粹的NIO”,我应该远离java.io
这是简化的代码(复制文件):得到FileChannel而不使用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(); 
} 

(代码非常简单:删除尝试,终于和循环)

我的问题是如何得到FileChannel或其他用于读取文件而不使用java.io的NIO类(FileInputStream)?

编辑:
Java 6中(或之前只)

回答

4

javadoc of FileChannel说:

此类没有定义打开现有文件或创建新的方法;这些方法可能会在未来的版本中添加。在此发行版中,可以通过调用该对象的getChannel方法从现有的FileInputStream,FileOutputStream或RandomAccessFile对象获取文件通道,该方法返回连接到相同底层文件的文件通道。

也就是说,对于java 1.6,如果不使用旧的java.io,您将无法获得FileChannel

4

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

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