如何通过JAVA NIO直接缓冲区拷贝文件
作者:暮色微凉
时间:2023-05-01
浏览:6
通过JAVANIO直接缓冲区拷贝文件/***通过JAVANIO直接缓冲区拷贝文件(内存映射文件)**@paramsourcePath源文件路径*@paramtargetPath目标文件路径*/publicstaticvoidcopyFileByChannelBufferd(StringsourcePath,StringtargetPath){FileChannelinChannel=null;FileChanneloutChannel=null;try{//获取通道,StandardOpenOption.
本文目录
通过JAVA NIO 直接缓冲区拷贝文件
/**
* 通过JAVA NIO 直接缓冲区拷贝文件(内存映射文件)
*
* @param sourcePath 源文件路径
* @param targetPath 目标文件路径
*/
public static void copyFileByChannelBufferd(String sourcePath, String targetPath) {
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
//获取通道,StandardOpenOption.READ表示可读,StandardOpenOption.WRITE表示可写,StandardOpenOption.CREATE表示可以创建
inChannel = FileChannel.open(Paths.get(sourcePath), StandardOpenOption.READ);
outChannel = FileChannel.open(Paths.get(targetPath), StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE);
//创建内存映射文件
MappedByteBuffer inMapped = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
MappedByteBuffer outMapped = outChannel.map(FileChannel.MapMode.READ_WRITE, 0, inChannel.size());
//直接操作内存映射文件
byte[] buf = new byte[inMapped.limit()];
inMapped.get(buf);
outMapped.put(buf);
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭流
try {
if (outChannel != null) {
outChannel.close();
}
if (inChannel != null) {
inChannel.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
作者最新文章
PDF怎么按页拆成单独文件?PDF按页拆分后怎么命名
2026-11-03 18:00
长网页转PDF怎么避免断图?网页转PDF怎么设置分页
2026-11-01 09:31
夸克资源库蓝光资源每日更新经典电视剧全集
2026-10-30 11:54
会声会影怎么导入音频 支持格式及步骤
2026-10-29 12:23
WPS表格常用功能实操:从录入到排序筛选的完整流程
2026-10-29 09:57
下一篇:
如何使用注解实现Redis缓存功能
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多

































