Channel
1.定义: Channel 表示 IO 源与目标打开的连接。Channel 类似于传统的“流”。只不过Stream是单向的,如:InputStream, OutputStream.而Channel是双向的,既可以用来进行读操作,又可以用来进行写操作。但Channel 本身不能直接访问数据,Channel 只能与Buffer 进行交互。
图解:
2.常用类
•FileChannel:用于读取、写入、映射和操作文件的通道。
•DatagramChannel:通过UDP 读写网络中的数据通道。
•SocketChannel:通过TCP 读写网络中的数据。
•ServerSocketChannel:可以监听新进来的TCP 连接,对每一个新进来的连接都会创建一个SocketChannel。
3.获取通道(Channel)
①对支持通道的对象调用
getChannel() 方法。支持通道的类如下:
- 本地IO
FileInputStream 、 FileOutputStream 、 RandomAccessFile - 网络IO
DatagramSocket 、 Socket 、 ServerSocket
②使用Files 类的静态方法newByteChannel() 获取字节通道。
③通过通道的静态方法open() 打开并返回指定通道。
4.读写操作
- 将Buffer 中数据写入Channel
例如:
//将Buffer中数据写入Channel中
int bytesWritten = inChannel.write(buf);
- 从Channel 读取数据到Buffer
例如:
//从Channel读取数据到Buffer中
int bytesRead = inChannel.read(buf);
5.用FileChannel进行文件读写
例1:写一个字符串到文件中
public void stringTOFileChannel () throws IOException {
//文件输出流
FileOutputStream out = new FileOutputStream("G:\\剑指BAT\\代码\\FileChannel.txt");
//要写入文件的字符串
String str = "Dream it possible";
//创建一个大小为512的字节缓冲区
ByteBuffer buf = ByteBuffer.allocate(512);
//将字符串存入ByteBuffer中
buf.put(str.getBytes());
//反转缓冲区(切换到读模式),以便读取ByteBuffer
buf.flip();
//获取输出文件的通道
FileChannel fo = out.getChannel();
System.out.println("写前 :"+buf);
//将字符串写入文件通道中
int write = fo.write(buf);
System.out.println("写后 :"+buf);
System.out.println("写入TXT文本的字节数 :"+write);
}
运行结果:
写前 :java.nio.HeapByteBuffer[pos=0 lim=17 cap=512]
写后 :java.nio.HeapByteBuffer[pos=17 lim=