java.nio.channels.AsynchronousChannel提供了异步写文件方法,
具体代码如下:

1public static void syncWrite(String path){ 2 File file = new File(path+"warn.log"); 3 if(!file.exists()) { 4 file.createNewFile(); 5 } 6 Path pathSyn = Paths.get(path+line+"warn.log"); 7 try { 8 AsynchronousFileChannel channel = AsynchronousFileChannel.open(pathSyn, StandardOpenOption.WRITE); 9 ByteBuffer buffer = ByteBuffer.allocate(1024); 10 buffer = ByteBuffer.wrap(clientSender.getBytes("utf-8")); 11 Future<Integer> future = channel.write(buffer, channel.size()); 12 channel.force(true); 13 while (!future.isDone()); 14 buffer.clear(); 15 channel.close(); 16 } catch (Exception e) { 17 e.printStackTrace(); 18 } 19}
异步NIO写文件