NIO(二) - 直接缓冲区 与 非直接缓冲区

9 篇文章 0 订阅
package com.xbb.demo;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 *
 * 四 : 直接缓冲区 与 非直接缓冲区
 *      非直接缓冲区 : 通过allocate()方法分配缓冲区.将缓冲区建立在JVM的内存中.
 *      直接缓冲区   : 通过allocateDirect()方法分配直接缓冲区,将缓冲区建立在物理内存中(某种情况下可提高效率)
 *
 */
public class ChannelDemo {

    /**
     * 非直接缓冲区
     * 通过通道完成文件的复制
     */
    @Test
    public void test1(){
        try(
            FileInputStream in = new FileInputStream("/Users/riverjin/Movies/nio/Java NIO.pdf");
            FileOutputStream out = new FileOutputStream("/Users/riverjin/Movies/nio/Java NIO2.pdf");
            FileChannel inChannel = in.getChannel();
            FileChannel outChannel = out.getChannel();
        ){
            // 分配缓冲区大小
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            // 将通道中的数据存入到缓冲区中
            while(inChannel.read(buffer) != -1){
                buffer.flip();
                outChannel.write(buffer);
                buffer.clear();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 直接缓冲区 (By 通道)
     */
    @Test
    public void test2(){
        try(
            FileChannel inChannel = FileChannel.open(Paths.get("/Users/riverjin/Movies/nio/Java NIO.pdf"), StandardOpenOption.READ);
            FileChannel outChannel = FileChannel.open(Paths.get("/Users/riverjin/Movies/nio/Java NIO3.pdf"),StandardOpenOption.CREATE,StandardOpenOption.WRITE);
        ){
            outChannel.transferFrom(inChannel,0,inChannel.size());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 直接缓冲区 (By 映射)
     */
    @Test
    public void test3(){
        try(
            FileChannel inChannel = FileChannel.open(Paths.get("/Users/riverjin/Movies/nio/Java NIO.pdf"), StandardOpenOption.READ);
            FileChannel outChannel = FileChannel.open(Paths.get("/Users/riverjin/Movies/nio/Java NIO3.pdf"),StandardOpenOption.READ,StandardOpenOption.CREATE,StandardOpenOption.WRITE);
        ){
            MappedByteBuffer inBuf  = inChannel.map(FileChannel.MapMode.READ_ONLY,0,inChannel.size());
            MappedByteBuffer outBuf = outChannel.map(FileChannel.MapMode.READ_WRITE,0,inChannel.size());
            byte[] buf = new byte[inBuf.limit()];
            outBuf.put(buf);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值