使用AsynchronousFileChannel类写入文件
import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousFileChannel; import java.nio.channels.CompletionHandler;/** n o w j a v a . c o m - 时代Java 提 供 **/ import java.nio.channels.WritePendingException; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; public class Main { public static void main(String[] args) { try (AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(Paths.get("/home/docs/asynchronous.txt"), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE)) { CompletionHandler<Integer, Object> handler = new CompletionHandler<Integer, Object>() {/*来 自 时 代 J a v a - N o w J a v a . c o m*/ @Override public void completed(Integer result, Object attachment) { System.out.println("Attachment: " + attachment + " " + result + " bytes written"); System.out.println("CompletionHandler Thread ID: " + Thread.currentThread().getId()); } @Override public void failed(Throwable e, Object attachment) { System.err.println("Attachment: " + attachment + " failed with:"); e.printStackTrace(); } }; System.out.println("Main Thread ID: " + Thread.currentThread().getId()); fileChannel.write(