package com.java7developer.chapter2.glab;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.nio.file.StandardOpenOption;
public class EfficientJackFileVisitor extends SimpleFileVisitor<Path> {
//and quick!
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.toString().endsWith(".txt")) {
AsynchronousFileChannel channel = AsynchronousFileChannel.open(file, StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(100_000);
Future<Integer> result = channel.read(buffer, 0);
Path dest = Paths.get(file.toString()+".backup");
if(!Files.exists(dest)) {
Files.createFile(dest);
}
try {
// makes a buffer ready for a new sequence of channel-write
buffer.flip();
//these are the most permissive StandardOpenOptions
AsynchronousFileChannel channelWrite = AsynchronousFileChannel.open(dest, StandardOpenOption.WRITE, StandardOpenOption.CREATE );
channelWrite.write(buffer,0);
Integer bytesRead = result.get();
System.out.println("Bytes read [" + bytesRead + "]");
} catch (InterruptedException ex) {
Logger.getLogger(EfficientJackFileVisitor.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(EfficientJackFileVisitor.class.getName()).log(Level.SEVERE, null, ex);
}
}
return FileVisitResult.CONTINUE;
}
}