java7 NIO2(8)The Asynchronous Channel API 异步通道API(二)
current.interrupt();
}
@Override
public void failed(Throwable exc, Object attachment) {
System.out.println(attachment);
System.out.println("Error:" + exc);
current.interrupt();
}
});
} catch (Exception ex) {
System.err.println(ex);
}
buffer.flip();
System.out.print(Charset.forName(encoding).decode(buffer));
buffer.clear();
// 异步文件写示例
ByteBuffer buffer1 = ByteBuffer
.wrap("The win keeps Nadal at the top of the heap in men's"
.getBytes());
Path path1 = Paths.get("/tmp", "store.txt");
try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel
.open(path1, StandardOpenOption.WRITE)) {
Future result = asynchronousFileChannel
.write(buffer1, 100);
while (!result.isDone()) {
System.out.println("Do something else while writing ...");
} www.2cto.com
System.out.println("Written done: " + result.isDone());
System.out.println("Bytes written: " + result.get());
// file lock
Future featureLock = asynchronousFileChannel.lock();
System.out.println("Waiting for the file to be locked ...");
FileLock lock = featureLock.get();
if (lock.isValid()) {
Future featureWrite = asynchronousFileChannel.write(
buffer, 0);
System.out.println("Waiting for the bytes to be written ...");
int written = featureWrite.get();
// or, use shortcut
// int written = asynchronousFileChannel.write(buffer,0).get();
System.out.println("I’ve written " + written + " bytes into "
+ path.getFileName() + " locked file!");
lock.release();
}
// asynchronousFileChannel.lock("Lock operation status:", new
// CompletionHandler() ;
} catch (Exception ex) {
System.err.println(ex);
}
}
// public static AsynchronousFileChannel open(Path file, Set< extends
// OpenOption> options,ExecutorService executor, FileAttribute< >... attrs)
// throws IOException
private static Set withOptions() {
final Set options = new TreeSet<>();
options.add(StandardOpenOption.READ);
return options;
}
// 使用AsynchronousFileChannel.open(path, withOptions(),
// taskExecutor))这个API对异步文件IO的处理
public static void asyFileChannel2() {
final int THREADS = 5;
ExecutorService taskExecutor = Executors.newFixedThreadPool(THREADS);
String encoding = System.getProperty("file.encoding");
List> list = new ArrayList<>();
int sheeps = 0;
Path path = Paths.get("/tmp",
"store.txt");
try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel
.open(path, withOptions(), taskExecutor)) {
for (int i = 0; i < 50; i++) {
Callable worker = new Callable() {
@Override
public ByteBuffer call() throws Exception {