通道(Channel)
基本概念
通道(Channel):由 java.nio.channels 包定义的。 Channel 表示 IO 源与目标打开的连接。Channel 类似于传统的“流”。只不过 Channel本身不能直接访问数据, Channel 只能与Buffer 进行交互。
- FileChannel:用于读取、写入、映射和操作文件的通道。
- DatagramChannel:通过 UDP 读写网络中的数据通道。
- SocketChannel:通过 TCP 读写网络中的数据。
- ServerSocketChannel:可以监听新进来的 TCP 连接,对每一个新进来的连接都会创建一个 SocketChannel。
获取通道
获取通道的一种方式是对支持通道的对象调用getChannel() 方法。支持通道的类如下:
- FileInputStream
- FileOutputStream
- RandomAccessFile
- DatagramSocket
- Socket
- ServerSocket
获取通道的其他方式是使用 Files 类的静态方法 newByteChannel() 获取字节通道。或者通过通道的静态方法 open() 打开并返回指定通道。
数据传输
将 Buffer 中数据写入 Channel
//将Buffer中数据写入Channel中
int bytesWritten = inChannel.write(buf);
从 Channel 读取数据到 Buffer
//将Buffer中数据写入Channel中
int bytesWritten = inChannel.read(buf);
例一(利用通道完成文件复制(非直接缓冲区)):
long start = System.currentTimeMillis();
FileInputStream fis = null;
FileOutputStream fos = null;
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
fis = new FileInputStream("d:/jdk-6u45-windows-x64.exe");
fos = new FileOutputStream("d:/jdk-6u45-windows-x642.exe");
// 1.获取通道
inChannel = fis.getChannel();
outChannel = fos.getChannel();
// 2.分配指定大小的缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
// 3.将通道中的数据写入缓冲区
while (inChannel.read(buffer) != -1) {
// 4.切换为读模式
buffer.flip();
// 5.将缓冲区中的数据写入到通道中
outChannel.write(buffer);
// 6.清空缓冲区
buffer.clear();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
this.close(fis, fos, inChannel, outChannel);
}
long end = System.currentTimeMillis();
System.out.println("共耗时:" + (end - start) + "毫秒。");
共耗时:1463毫秒。
例二(使用直接缓冲区完成文件复制(内存映射文件)):
long start = System.currentTimeMillis();
String as[] = {};
OpenOption aopenoption[] = { StandardOpenOption.READ,
StandardOpenOption.WRITE, StandardOpenOption.CREATE };
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
inChannel = FileChannel.open(
Paths.get("d:/jdk-6u45-windows-x64.exe", as), aopenoption);
outChannel = FileChannel.open(
Paths.get("d:/jdk-6u45-windows-x641.exe", as), aopenoption);
// 内存映射文件
MappedByteBuffer inMappedBuf = inChannel.map(MapMode.READ_ONLY, 0,
inChannel.size());
MappedByteBuffer outMappedBuf = outChannel.map(MapMode.READ_WRITE,
0, inChannel.size());
// 直接对缓冲区进行数据读写操作
byte[] dst = new byte[inMappedBuf.limit()];
inMappedBuf.get(dst);
outMappedBuf.put(dst);
} catch (IOException e) {
e.printStackTrace();
} finally {
this.close(null, null, inChannel, outChannel);
}
long end = System.currentTimeMillis();
System.out.println("共耗时:" + (end - start) + "毫秒。");
共耗时:126毫秒。