java面试

NIO详解

2019-04-25  本文已影响122人  AKyS佐毅

1、BIO与NIO

IO(BIO)和NIO区别:其本质就是阻塞和非阻塞的区别

2、NIO概述

什么是NIO?

image.png image.png

非直接缓冲区:

直接缓冲区:

public class DirectCache {

    public static void main(String[] args) {
        DirectCache directCache = new DirectCache();
        try {
            directCache.test2();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 使用直接缓冲区完成文件的复制(内存映射文件)
    static public void test2() throws IOException {  // 28
        long start = System.currentTimeMillis();
        FileChannel inChannel = FileChannel.open(Paths.get("/Users/kevin/Desktop/互动电视接口文档.docx"), StandardOpenOption.READ);
        FileChannel outChannel = FileChannel.open(Paths.get("/Users/kevin/Desktop/互动电视接口文档2.docx"), StandardOpenOption.WRITE,
                StandardOpenOption.READ, StandardOpenOption.CREATE);
        // 内存映射文件
        MappedByteBuffer inMappedByteBuf = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
        MappedByteBuffer outMappedByteBuffer = outChannel.map(FileChannel.MapMode.READ_WRITE, 0, inChannel.size());
        // 直接对缓冲区进行数据的读写操作
        byte[] dsf = new byte[inMappedByteBuf.limit()];
        inMappedByteBuf.get(dsf);
        outMappedByteBuffer.put(dsf);
        inChannel.close();
        outChannel.close();
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }

    // 1.利用通道完成文件的复制(非直接缓冲区)
    static public void test1() throws IOException { // 39

        long start = System.currentTimeMillis();
        FileInputStream fis = new FileInputStream("/Users/kevin/Desktop/互动电视接口文档.docx");
        FileOutputStream fos = new FileOutputStream("/Users/kevin/Desktop/互动电视接口文档2.docx");
        // ①获取通道
        FileChannel inChannel = fis.getChannel();
        FileChannel outChannel = fos.getChannel();
        // ②分配指定大小的缓冲区
        ByteBuffer buf = ByteBuffer.allocate(1024);
        while (inChannel.read(buf) != -1) {
            buf.flip();// 切换为读取数据
            // ③将缓冲区中的数据写入通道中
            outChannel.write(buf);
            buf.clear();
        }
        outChannel.close();
        inChannel.close();
        fos.close();
        fis.close();
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读