NIO之Channel(Netty三)

12 篇文章 0 订阅

1.channel通道可以同时进行读写,而流只能读或者只能写,通道可以实现异步读写数据,通道可以从缓冲区读数据,也可以写数据到缓冲区。Channel在NIO中是一个接口,常用的channel类有FileChannel,DatagramChannel,serverSocketChannel,socketChannel,FileChannel用于文件的数据读写,DatagramChannel用于UDP的数据读写,ServerSocketChannel和SocketChannel用于TCP的数据读写。

2.FileChannel主要用来对本地文件进行IO操作,常见的方法有

public int read(ByteBuffer dst)从通道读取数据并放到缓冲区中
publict int write(ByteBuffer src)吧缓冲区的数据写到通道中
public long transferFrom(ReadableByteChannel src,long postion,long count)从目标通道复制数据到当前通道
pubLic long transterTo(long position,long count, WriteableByteChannel target)将数据从当前通道复制给目标通道
public class ChannelTest {
    public static void main(String[] args) throws Exception{
        String str = "hello,尚硅谷";
        // 创建一个输出流
        FileOutputStream fileOutputStream = new FileOutputStream("D:\\a.txt");
        FileChannel fileChannel = fileOutputStream.getChannel();
        // 创建一个缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        // 将str放入byteBuffer
        byteBuffer.put(str.getBytes());
        // buffer切换读写方式
        byteBuffer.flip();
        // 将byteBuffer数据写入到fileChannel
        fileChannel.write(byteBuffer);
        fileOutputStream.close();

    }
}

文件拷贝:

public class FileChannel01 {
    public static void main(String[] args) throws Exception{
        // 文件输入流
        FileInputStream fileInputStream = new FileInputStream("1.txt");
        FileChannel fileChannel = fileInputStream.getChannel();

        // 文件输出流
        FileOutputStream fileOutputStream = new FileOutputStream("2.txt");
        FileChannel fileChannel1 = fileOutputStream.getChannel();

        // 创建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(512);
        while(true){

            // 清空buffer
            byteBuffer.clear();

            int read = fileChannel.read(byteBuffer);
            if(read == -1){
                break;
            }
            // 将buffer中的数据写入到fileChannel01--2.txt
            byteBuffer.flip();
            fileChannel1.write(byteBuffer);
        }
        fileInputStream.close();
        fileOutputStream.close();
    }
}

transferFrom方法实现文件拷贝:

public class FileChannel02 {
    public static void main(String[] args) throws Exception{
        // 创建相关流
        FileInputStream fileInputStream = new FileInputStream("1.txt");
        FileOutputStream fileOutputStream = new FileOutputStream("3.txt");
        // 获取各个流对应的channel
        FileChannel sourceCh = fileInputStream.getChannel();
        FileChannel destCh = fileOutputStream.getChannel();

        // 使用transferForm完成拷贝
        destCh.transferFrom(sourceCh,0,sourceCh.size());
        // 关闭资源
        sourceCh.close();
        destCh.close();
        fileInputStream.close();
        fileOutputStream.close();
    }
}

// mappedByteBuffer可让文件直接在内存中修改,操作系统不需要在拷贝一次
public class MappedByteBufferTest {
    public static void main(String[] args) throws Exception{
        RandomAccessFile randomAccessFile = new RandomAccessFile("1.txt","rw");
        // 获取对应的通道
        FileChannel fileChannel = randomAccessFile.getChannel();
        /**
         * 参数一:使用读写模式
         * 参数二:可以直接修改的其实位置
         * 参数三:要修改的内存最大位置
         */
        MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE,0,5);
        mappedByteBuffer.put(0,(byte)'H');
        mappedByteBuffer.put(3,(byte)'5');
        randomAccessFile.close();
        System.out.println("修改成功");
    }
}
/**
 * Scattering:将数据写入到buffer时,可以采用buffer数组,依次写入
 * Gathering:从buffer读取数据时,可以采用buffer数组,依次读
 */
public class ScatteringAndGatheringTest {
    public static void main(String[] args) throws Exception{
        // 使用ServerSocketChannel和SocketChannel网络
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);
        // 绑定端口到socket,并启动
        serverSocketChannel.socket().bind(inetSocketAddress);
        // 创建buffer数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);
        // 客户端使用telnet连接
        SocketChannel socketChannel = serverSocketChannel.accept();
        int messageLenght = 8;
        while(true){
            int byteRead = 0;
            while(byteRead<messageLenght){
                long l = socketChannel.read(byteBuffers);
                byteRead += l;
                System.out.println("byteRead="+byteRead);
                Arrays.asList(byteBuffers).stream()
                        .map(byteBuffer -> "position="+byteBuffer.position()+", limit="+
                                byteBuffer.limit()).forEach(System.out::println);
            }
            // 将所有buffer进行读写切换
            Arrays.asList(byteBuffers).forEach(buffer->buffer.flip());

            // 将数据显示给客户端
            long byteWrite = 0;
            while(byteWrite<messageLenght){
                long l = socketChannel.write(byteBuffers);
                byteWrite += l;
            }
            // 将所有buffer进行clear
            Arrays.asList(byteBuffers).forEach(buffer->buffer.clear());
            System.out.println("byteRead:="+byteRead+"byteWrite="+byteWrite);
        }
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值