AsynchronousFileChannel写数据
public class TryNio implements CompletionHandler<Integer, AsynchronousFileChannel> {
int position = 0;
AsynchronousFileChannel channel = null;
ByteBuffer buffer = null;
public void completed(Integer result, AsynchronousFileChannel attachment) {
System.out.println ("Bytes written: " + result);
}
public void failed(Throwable exc, AsynchronousFileChannel attachment) {
System.err.println ("Error!");
exc.printStackTrace();
}
public void doIt(String inFileName) {
Path file = Paths.get(inFileName);
try {
channel = AsynchronousFileChannel.open(file, StandardOpenOption.WRITE);
buffer = ByteBuffer.allocate(1024);
Scanner in = new Scanner(System.in);
for(;;) {
if(in.hasNextLine()) {
buffer.put(in.nextLine().getBytes());
buffer.flip();
channel.write(buffer, position, channel, this);
buffer.clear();
}
}
} catch (IOException e) {
System.err.println ("Could not open file: " + file+ e);
System.exit(1);
}
}
public static void main (String [] args) {
TryNio tn = new TryNio();
tn.doIt("/var/log/syslog");
}
}