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

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();
        }
    }
}

上一篇:MySQL忘记密码


下一篇:记录一下 reactor单线程代码实现