1.2.2 Channel 通道
特点:
- 可以同时读写
- 可以异步读写
- 可以从缓冲区读写数据
常用Channel
- FileChannel – 文件读写
- DatagramChannel – UDP读写
- ServerSocketChannel – TCP读写
- SocketChannel – TCP读写
流程
当客户端连接服务器时,服务器上的ServerSocketChannel会创建一个与客户端相对应的SocketChannel
1.2.2.1 FileChannel
读写操作都是通道视角
- write方法 – 缓冲区 == 》通道
输出示例
流程:
- 创建输出流
- 字符串放入buffer
- 从输出流中获取fileChannel
- 缓冲区内容写入通道
- 通道写入文件
- 关闭输出流
public static void main(String[] args) throws Exception{
String str = "hello world!";
//创建一个输出流->channel
FileOutputStream fileOutputStream = new FileOutputStream("F:\\FTHZ\\file01.txt");
//通过输出流获取对应的 FileChannel
FileChannel fileChannel = fileOutputStream.getChannel();
//创建一个缓冲区
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
//将String写入byteBuffer
byteBuffer.put(str.getBytes());
//读写切换
byteBuffer.flip();
//写入channel
fileChannel.write(byteBuffer);
fileOutputStream.close()<