通过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直接缓冲区拷贝文件的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号