简体   繁体   中英

get FileChannel without using java.io.* (use pure NIO)

Recently I got a comment to this answer that I should stay away from java.io if I want to use "pure NIO".
This is the simplified code (copy a file):

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();
}

(code extremely simplified: removed try-finally and loop)

My question is how to get a FileChannel or other NIO class for reading a file without using java.io ( FileInputStream )?

EDIT:
Java 6 (or before only)

The javadoc of FileChannel says:

This class does not define methods for opening existing files or for creating new ones; such methods may be added in a future release. In this release a file channel can be obtained from an existing FileInputStream, FileOutputStream, or RandomAccessFile object by invoking that object's getChannel method, which returns a file channel that is connected to the same underlying file.

That is, with java 1.6 you can't get a FileChannel without using old java.io .

Java 6 only has FileInputStream.getChannel() , FileOutputStream.getChannel() , and RandomAccessFile.getChannel()

Java 7 has java.nio.channels.FileChannel.open(...) and java.nio.Files.newByteChannel(...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM