java.nio.channels.AsynchronousChannel提供了异步写文件方法,
具体代码如下:
public static void syncWrite(String path){
File file = new File(path+"warn.log");
if(!file.exists()) {
file.createNewFile();
}
Path pathSyn = Paths.get(path+line+"warn.log");
try {
AsynchronousFileChannel channel = AsynchronousFileChannel.open(pathSyn, StandardOpenOption.WRITE);
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer = ByteBuffer.wrap(clientSender.getBytes("utf-8"));
Future<Integer> future = channel.write(buffer, channel.size());
channel.force(true);
while (!future.isDone());
buffer.clear();
channel.close();
} catch (Exception e) {
e.printStackTrace();
}
}
异步NIO写文件