Java NIO之Buffer 一文介绍过 缓冲区Buffer。Channel是Java NIO的核心组件之一,用于连接源节点和目标节点,负责缓冲区数据的传输,分类如下:
(1)FileChannel,文件通道
(2)SocketChannel和ServerSocketChannel,通过TCP读写网络中的数据
(3)DatagramChannel,通过UDP读写网络中的数据
获取通道的方法:
(1)本地IO:FileInputStream,FileOutputStream,RandomAccessFile实例的getChannel方法
(2)SocketChannel,ServerSocketChannel,DatagramChannel的open()方法
(3)java.nio.file.Files工具类下的newByteChannel方法
下面演示,通过NIO的通道Channel,实现文件的复制操作:
// 文件复制,使用非直接缓冲区
public static void testCopyFileByChannel(String srcFileName,String destFileName){
FileChannel inChannel = null;
FileChannel outChannel = null;
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(srcFileName);
fileOutputStream = new FileOutputStream(destFileName);
// 1. 获取通道
inChannel = fileInputStream.getChannel();
outChannel = fileOutputStream.getChannel();
// 2. 分配指定缓冲区大小
ByteBuffer buffer = ByteBuffer.allocate(1024);
// 循环读写
// 3.向缓冲区写数据
while (inChannel.read(buffer) != -1){
// 4.切换为读模式
buffer.flip();
// 5.从缓冲区读数据
outChannel.write(buffer);
// 6.清空缓冲区
buffer.clear();
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (fileInputStream != null){
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream != null){
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inChannel != null){
try {
inChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outChannel != null){
try {
outChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
其实,就是分为了三步:
(1)获取通道
(2)分配缓冲区
(3)读写数据
这种方式,虽然有缓冲区,但是读写速度并不快,因为使用的不是直接缓冲区,关于直接缓冲区和非直接缓冲区可自行了解,简单来说,直接缓冲区,省去了数据在用户态和内核态之间的数据复制过程,所以会比较快,下面是一个使用直接缓冲区的简单示例:
// 通道之间的数据传输,使用直接缓冲区
public static void testChannel2Channel() throws IOException {
// 获取通道
FileChannel inChannel = FileChannel.open(Paths.get("D:\\1.avi"), StandardOpenOption.READ);
FileChannel outChannel = FileChannel.open(Paths.get("D:\\2.avi"), StandardOpenOption.READ,StandardOpenOption.WRITE,StandardOpenOption.CREATE);
// 通过调用 transferTo 或者 transferFrom方法实现复制
// inChannel.transferTo(0,inChannel.size(),outChannel);
outChannel.transferFrom(inChannel,0,inChannel.size());
inChannel.close();
outChannel.close();
}
通过大文件的数据传输过程比较,就可以发现,使用直接缓冲区速度快了很多很多
之前也写过一篇文章,Java使用NIO实现大文件下载