简介:
- 直接缓冲区:直接缓冲区则不再通过内核地址空间和用户地址空间的缓存数据的复制传递,而是在物理内存中申请了一块空间,这块空间映射到内核地址空间和用户地址空间,应用程序与磁盘之间的数据存取之间通过这块直接申请的物理内存进行。通过 allocateDirect() 方法分配直接缓冲区,将缓冲区建立在物理内存中。可以提高效率。
- 非直接缓冲区:NIO通过通道连接磁盘文件与应用程序,通过缓冲区存取数据进行双向的数据传输。物理磁盘的存取是操作系统进行管理的,与物理磁盘的数据操作需要经过内核地址空间;而我们的Java应用程序是通过JVM分配的缓冲空间。有点雷同于一个属于核心态,一个属于应用态的意思,而数据需要在内核地址空间和用户地址空间,在操作系统和JVM之间进行数据的来回拷贝,无形中增加的中间环节使得效率与后面要提的之间缓冲区相比偏低。即通过 allocate() 方法分配缓冲区,将缓冲区建立在 JVM 的内存中。
一、通过通道使用非直接缓冲区来完成文件的复制
通过声明流对象来读取文件信息,在文件流转换为通道对象,其次使用通道对象分配一块缓冲区来对文件进行读写输出。具体示例代码如下:
public void copyFile(){
FileInputStream fis = null;
FileOutputStream fos = null;
//获取通道
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
fis = new FileInputStream("d:/1.mkv");
fos = new FileOutputStream("d:/2.mkv");
inChannel = fis.getChannel();
outChannel = fos.getChannel();
//分配指定大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
//将通道中的数据存入缓冲区中
while(inChannel.read(buf) != -1){
buf.flip(); //切换读取数据的模式
//将缓冲区中的数据写入通道中
outChannel.write(buf);
buf.clear(); //清空缓冲区
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(outChannel != null){
try {
outChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inChannel != null){
try {
inChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
二、使用直接缓冲区实现的方式
方式一:
使用直接缓冲区通过内存映射文件来达到文件复制的目的,具体示例如下:
public void copyFiles() throws IOException{
FileChannel inChannel = FileChannel.open(Paths.get("d:/copy.mp4"), StandardOpenOption.READ);
FileChannel outChannel = FileChannel.open(Paths.get("d:/past.mp4"), StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE);
//内存映射文件
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);
inChannel.close();
outChannel.close();
}
该方式存在一定的安全隐患,因为缓冲区不在是在JVM中创建而是物理内存中直接创建的,所以数据写完后便不在归程序所管控,占用资源并不会立即释放,gc并不会马上被调用。
方式二:
通过NIO的通道间的数据传输可直接实现文件的复制功能,具体示例如下:
public void copyFiles() throws IOException{
FileChannel inChannel = FileChannel.open(Paths.get("d:/copy.mp4"), StandardOpenOption.READ);
FileChannel outChannel = FileChannel.open(Paths.get("d:/past.mp4"), StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE);
//使用输入通道来实现文件输出
// inChannel.transferTo(0, inChannel.size(), outChannel);
//使用输出通道
outChannel.transferFrom(inChannel, 0, inChannel.size());
inChannel.close();
outChannel.close();
}
本文探讨了Java NIO中的直接缓冲区和非直接缓冲区在文件复制操作中的应用。直接缓冲区通过内存映射文件减少数据拷贝,提高效率,但可能导致资源占用不及时释放。非直接缓冲区则涉及内核地址空间和用户地址空间的数据拷贝。示例代码展示了两种缓冲区在文件复制中的实现方式,包括通道间的传输和内存映射文件的方法。

441

被折叠的 条评论
为什么被折叠?



