直接内存NIO和传统IO读取文件的区别

    public static void main(String[] args) {
        io();
        directBufferTest();
    }

    private static void directBufferTest() {
        long start = System.nanoTime();
        try (FileChannel from = new FileInputStream(FROM).getChannel();
             FileChannel to = new FileOutputStream(TO).getChannel()){
            ByteBuffer buffer = ByteBuffer.allocateDirect(_1MB);
            while (true) {
               int len = from.read(buffer);
               if (len == -1) {
                   break;
               }
               buffer.flip();
               to.write(buffer);
               buffer.clear();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        long end = System.nanoTime();
        System.out.println("NOI耗时:" + (end - start)/1000000 + "ms");
    }

    private static void io() {
        long start = System.nanoTime();
        try (FileInputStream from = new FileInputStream(FROM);
        FileOutputStream to = new FileOutputStream(TO)) {
            byte[] buffer = new byte[_1MB];
            while (true) {
                int read = from.read(buffer);
                if (read == -1) {
                    break;
                }
                to.write(buffer, 0, read);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        long end = System.nanoTime();
        System.out.println("io耗时:" + (end - start)/1000000 + "ms");
    }
}
posted @ 2025-09-04 09:26  紫川先生  阅读(4)  评论(0)    收藏  举报