- 通道(Channel):由 java.nio.channels 包定义的。Channel 表示 IO 源与目标打开的连接。Channel 类似于传统的“流”。只不过 Channel本身不能直接访问数据,Channel 只能与Buffer 进行交互。
Java 为 Channel 接口提供的最主要实现类如下:
- FileChannel:用于读取、写入、映射和操作文件的通道。
- DatagramChannel:通过 UDP 读写网络中的数据通道。
- SocketChannel:通过 TCP 读写网络中的数据。
- ServerSocketChannel:可以监听新进来的 TCP 连接,对每一个新进来的连接都会创建一个 SocketChannel。
获取通道
- 一种方式是对支持通道的对象调用getChannel() 方法。支持通道的类如下:
- FileInputStream
- FileOutputStream
- RandomAccessFile
- DatagramSocket
- Socket
- ServerSocket
- 获取通道的其他方式是使用 Files 类的静态方法 newByteChannel() 获取字节通道。或者通过通道的静态方法 open() 打开并返回指定通道。
通道的数据传输
- write(buf)写数据
- read (buf) 读数据
直接缓冲区:
public void test4() {
// 效率高, 不是特别 稳定
try {
FileChannel inChannel = FileChannel.open(Paths.get( "a.png"), StandardOpenOption.READ);
FileChannel outChannel = FileChannel.open(Paths.get("3.png"), StandardOpenOption.WRITE, StandardOpenOption.READ,StandardOpenOption.CREATE);
// 内存映射文件 ,缓冲区在物理内存中 只有ByteBuffer 支持
MappedByteBuffer inMapBuf = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
MappedByteBuffer outMapBuf = outChannel.map(FileChannel.MapMode.READ_WRITE, 0, inChannel.size());
// 直接对缓冲区进行数据读写操作
byte[] by = new byte[inMapBuf.limit()];
inMapBuf.get(by);
outMapBuf.put(by); //outMapBuf 可读可写,因此 通道也要把 读 加上
inChannel.close();
outChannel.close();
} catch (IOException e) {
System.out.println("哦豁 ,错了");
e.printStackTrace();
}
}
非直接缓冲区:
public void test3() {
FileInputStream fis = null;
FileOutputStream fos = null;
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
fis = new FileInputStream("a.png");
fos = new FileOutputStream("2.png");
//获取通道
inChannel = fis.getChannel();
outChannel = fos.getChannel();
//分配指定大小的缓存区
ByteBuffer buffer = ByteBuffer.allocate(1024);
//将通道的数据读入缓冲区
while (inChannel.read(buffer) != -1) {
// 切换 到读取数据的模式
buffer.flip();
// 将缓冲区的数据写到通道
outChannel.write(buffer);
// 清空缓冲区
buffer.clear();
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
try {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
if (fis != null)
fis.close();
if (fos != null)
fos.close();
} catch (IOException e) {
}
}