其他分享
首页 > 其他分享> > NIO(二) - 直接缓冲区 与 非直接缓冲区

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

标签:NIO,FileChannel,inChannel,缓冲区,import,StandardOpenOption,直接,nio
来源: https://blog.csdn.net/jinjianghai/article/details/98035734