NIO File Copy Example
A minimal NIO file copy example utilizing channles.
1// initialize files form URIs and check paths/permissions
2Path inputFile = Paths.get(inputFileName);
3assert Files.exists(inputFile) == true;
4assert Files.isReadable(inputFile) == true;
5
6Path outputFile = Paths.get(outputFileName);
7assert Files.exists(outputFile.getParent()) == false;
8assert Files.isWritable(outputFile.getParent()) == false;
9
10// open file reader
11SeekableByteChannel inputChannel = Files.newByteChannel(inputFile);
12ByteBuffer byteBuffer = ByteBuffer.allocate(bufferSize);
13Charset charset = Charset.forName("US-ASCII");
14
15// open writer, overwrite target file if it exists
16Set options = new HashSet();
17options.add(StandardOpenOption.CREATE);
18options.add(StandardOpenOption.WRITE);
19FileChannel outputChannel = FileChannel.open(outputFile, options);
20
21// loop over channel
22while (inputChannel.read(byteBuffer) > 0) {
23 // flip for from input to output, then write to console
24 byteBuffer.flip();
25 System.out.print(charset.decode(byteBuffer));
26
27 // rewind so we can read buffer again from the beginning
28 // the write to file output channel
29 byteBuffer.rewind();
30 outputChannel.write(byteBuffer);
31
32 // flip channel from output to input again.
33 byteBuffer.flip();
34}
35outputChannel.close();