Java之NIO

缓冲区

缓冲区(Buffer):在 Java NIO 中负责数据的存取。缓冲区就是数组。用于存储不同数据类型的数据。根据数据类型不同(boolean 除外),提供了相应类型的缓冲区:

  • ByteBuffer,
  • CharBuffer,
  • IntBuffer,
  • LongBuffer,
  • ShortBuffe
  • DoubleBuffer,
  • FloatBuffer, ,
  • MappedByteBuffer

上述缓冲区的管理方式几乎一致,通过 allocate() 方法获取缓冲区

 

缓冲区存取数据的两个核心方法:

  • put() : 存入数据到缓冲区中
  • get() : 获取缓冲区中的数据

 

缓冲区中的四个核心属性:

 

  • capacity : 容量,表示缓冲区中最大存储数据的容量。一旦声明不能改变。
  • limit : 界限,表示缓冲区中可以操作数据的大小。(limit 后数据不能进行读写)
  • position : 位置,表示缓冲区中正在操作数据的位置。
  • mark : 标记,表示记录当前 position 的位置。可以通过 reset() 恢复到 mark 的位置

说明:0 <= mark <= position <= limit <= capacity

接缓冲区与非直接缓冲区:

  • 非直接缓冲区:通过 allocate() 方法分配缓冲区,将缓冲区建立在 JVM 的内存中
  • 直接缓冲区:通过 allocateDirect() 方法分配直接缓冲区,将缓冲区建立在物理内存中。可以提高效率

常用操作方法:

  • allocate() 获取缓冲区
  • put() : 存入数据到缓冲区中
  • flip():切换读取数据模式
  • get() : 读取缓冲区中的数据
  • rewind():可重复读
  • clear():清空缓冲区. 但是缓冲区中的数据依然存在
  • mark() : 标记
  • reset() : 恢复到 mark 的位置
  • hasRemaining():判断缓冲区中是否还有剩余数据
  • remaining():获取缓冲区中可以操作的数量
  • limit():

 

范例1:Buffer的使用

 @Test
    public void test1(){
        // 1. 创建一个指定大小的缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        System.out.println(byteBuffer.position());
        System.out.println(byteBuffer.limit());
        System.out.println(byteBuffer.capacity());

        // 2. 使用put()方法放入数组到缓冲区
        byteBuffer.put("hello".getBytes());
        System.out.println("-----------------put()----------------");
        System.out.println(byteBuffer.position());
        System.out.println(byteBuffer.limit());
        System.out.println(byteBuffer.capacity());

        // 3. 调用flip()方法切换到读取模式
        byteBuffer.flip();
        System.out.println("-----------------flip()----------------");
        System.out.println(byteBuffer.position());
        System.out.println(byteBuffer.limit());
        System.out.println(byteBuffer.capacity());


        // 4. 使用get()方法读取缓冲区中的数据
        byte[] dist = new byte[byteBuffer.limit()];
        byteBuffer.get(dist);
        System.out.println(new String(dist));
        System.out.println("-----------------get()----------------");
        System.out.println(byteBuffer.position());
        System.out.println(byteBuffer.limit());
        System.out.println(byteBuffer.capacity());

        // 5. 调用rewind()方法可重复读
        byteBuffer.rewind();
        System.out.println("-----------------rewind()----------------");
        System.out.println(byteBuffer.position());
        System.out.println(byteBuffer.limit());
        System.out.println(byteBuffer.capacity());

        //6. clear() : 清空缓冲区. 但是缓冲区中的数据依然存在,但是处于“被遗忘”状态
        byteBuffer.clear();
        System.out.println("-----------------clear()----------------");
        System.out.println(byteBuffer.position());
        System.out.println(byteBuffer.limit());
        System.out.println(byteBuffer.capacity());
        System.out.println((char)byteBuffer.get());
    }

 

 

 

范例2:

 

 

 

通道

通道(Channel):通道是一个完全独立的处理器, 用于源节点与目标节点的连接。在 Java NIO 中负责缓冲区中数据的传输。Channel 本身不存储数据,因此需要配合缓冲区进行传输。通道的主要实现类:

java.nio.channels.Channel 接口:

|--FileChannel 用于读写文件的通道

|--SocketChannel 通过TCP读写网络中的数据

|--ServerSocketChannel 可以监听新进行的TCP连接,对每一个新进来的连接都会创建一个SocketChannel

|--DatagramChannel 通过UDP读写网络中的数据

三、获取通道

  • Java 针对支持通道的类提供了 getChannel() 方法

本地 IO:

  • FileInputStream/FileOutputStream
  • RandomAccessFile

网络IO:

  • Socket
  • ServerSocket
  • DatagramSocket

 

  • 在 JDK 1.7 中的 NIO.2 针对各个通道提供了静态方法 open()
  • 在 JDK 1.7 中的 NIO.2 的 Files 工具类的 newByteChannel()

示例1:利用通道完成文件复制(循环读取)

  /**
     * 利用通道完成文件复制(循环读取)
     */
    @Test
    public void test3(){
        try (FileInputStream in = new FileInputStream("/Users/isaiah/temp/etcd.tar");
            FileOutputStream out = new FileOutputStream("/Users/isaiah/temp/test.tar");
        ) {
            FileChannel inChannel = in.getChannel();
            FileChannel outChannel = out.getChannel();

            ByteBuffer buff = ByteBuffer.allocate(1024);
            // 循环读取数据
            while (inChannel.read(buff) != -1){
                buff.flip();
                outChannel.write(buff);
                buff.clear();
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

 

示例2:利用通道完成文件复制(内存映射文件)

 /**
     * 利用通道完成文件复制(内存映射文件)
     */
    @Test
    public void test4(){
        try(
                FileChannel inChannel = FileChannel.open(Paths.get("/Users/isaiah/temp/a.out"), StandardOpenOption.READ);
                FileChannel outChannel = FileChannel.open(Paths.get("/Users/isaiah/temp/b.out"), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        ){
            long start = System.currentTimeMillis();
            MappedByteBuffer inBuffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
            MappedByteBuffer outBuffer = outChannel.map(FileChannel.MapMode.READ_WRITE,0, outChannel.size());
            byte[] buff = new byte[inBuffer.limit()];
            inBuffer.get(buff);
            outBuffer.put(buff);
            long end = System.currentTimeMillis();
            System.out.println("耗费时间为:" + (end - start));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

 

示例3:通道之间的数据传输(直接缓冲区)

  /**
     * 通道之间的数据传输(直接缓冲区)
     */
    @Test
    public void test5(){
        try (FileChannel inChannel = FileChannel.open(Paths.get("/Users/isaiah/temp/a.out"), StandardOpenOption.READ);
        FileChannel outChannel = FileChannel.open(Paths.get("/Users/isaiah/temp/b.out"), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);

        ) {
            outChannel.transferFrom(inChannel, 0, inChannel.size());
            //inChannel.transferTo(0, inChannel.size(), outChannel);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值