Java 异步NIO写文件,无队列线程池方案

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写文件

 

posted @ 2018-03-01 14:50  川雨淅  阅读(265)  评论(0编辑  收藏  举报