这篇文章主要为大家展示了“如何通过JAVA NIO直接缓冲区拷贝文件”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“如何通过JAVA NIO直接缓冲区拷贝文件”这篇文章吧。
通过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();
}
}
}
以上是“如何通过JAVA NIO直接缓冲区拷贝文件”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。