【Netty系列】NIO编程案例(Channel)

一、通道(Channel)使用案例

NIO 的通道类似于流,但有些区别如下:通道可以同时进行读写,而流只能读或者只能写;通道可以实现异步读写数据;通道可以从缓冲读数据,也可以写数据到缓冲。
BIO 中的 Stream 是单向的,例如 FileInputStream 对象只能进行读取数据的操作,而 NIO 中的通道(Channel)是双向的,可以读操作,也可以写操作
常用的 Channel 类有: FileChannelDatagramChannelServerSocketChannelSocketChannel 。【ServerSocketChannel 类似 ServerSocketSocketChannel 类似 Socket】。其中FileChannel 用于文件的数据读写,DatagramChannel 用于 UDP 的数据读写,ServerSocketChannelSocketChannel 用于 TCP 的数据读写。

1. FileChannel类

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

  • public int read(ByteBuffer dst),从通道读取数据并放到缓冲区中
  • public int write(ByteBuffer src),把缓冲区的数据写到通道中
  • public long transferFrom(ReadableByteChannel src, long position, long count),从目标通道中复制数据到当前通道
  • public long transferTo(long position, long count, WritableByteChannel target),把数据从当前通道复制给目标通道

案例1:本地文件写数据

hello,lwz字符串写入到本地文件E:\\file01.txt中:

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NIOTest1 {
   
    public static void main(String[] args) throws IOException {
   
        String str = "hello,lwz";  // 输出字符串
        // 创建一个输出流 -> channel
        FileOutputStream fileOutputStream = new FileOutputStream("E:\\file01.txt");
        // 通过fileOutputStream获取对应的FileChannel
        FileChannel channel = fileOutputStream.getChannel();
        // 创建缓冲区,容量为1024字节
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

你可能感兴趣的:(【Netty系列】NIO编程案例(Channel))