import java.nio.*;
import java.nio.channels.*;
import java.nio.file.*;
import java.io.IOException;
public class TryNio implements CompletionHandler<Integer, AsynchronousFileChannel> {
// need to keep track of the next position.
int position = 0;
AsynchronousFileChannel channel = null;
ByteBuffer buffer = null;
public void completed(Integer result, AsynchronousFileChannel attachment) {
// if result is -1 means nothing was read.
if (result != -1) {
position += result; // don't read the same text again.
// your output command.
System.out.println(new String(buffer.array(), 0, result));
buffer.clear(); // reset the buffer so you can read more.
}
// initiate another asynchronous read, with this.
attachment.read(buffer, position, attachment, this);
}
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);
} catch (IOException e) {
System.err.println ("Could not open file: " + file+ e);
System.exit(1); // yeah. heh.
}
buffer = ByteBuffer.allocate(1000);
// start off the asynch read.
channel.read(buffer, position, channel, this);
// this method now exits, thread returns to main and waits for user input.
}
public static void main (String [] args) {
TryNio tn = new TryNio();
String inFileName = "/var/log/syslog";
tn.doIt(inFileName);
// wait fur user to press a key otherwise java exits because the
// asynch thread isn't important enough to keep it running.
try { System.in.read(); } catch (IOException e) { }
}
}
版权声明:本文为qq_27870421原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。