如何通过JAVA NIO非直接缓冲区拷贝文件
作者:归人云淡风轻
时间:2023-05-04
浏览:6
通过JAVANIO非直接缓冲区拷贝文件/***通过JAVANIO非直接缓冲区拷贝文件**@paramsourcePath源文件路径*@paramtargetPath目标文件路径*/publicstaticvoidcopyFileByChannel(StringsourcePath,StringtargetPath){FileChanneloutChannel=null;FileChannelinChannel=null;FileInputStreamfis=null;FileOutputStreamfos
本文目录
通过JAVA NIO 非直接缓冲区拷贝文件
/**
* 通过JAVA NIO 非直接缓冲区拷贝文件
*
* @param sourcePath 源文件路径
* @param targetPath 目标文件路径
*/
public static void copyFileByChannel(String sourcePath, String targetPath) {
FileChannel outChannel = null;
FileChannel inChannel = null;
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(sourcePath);
fos = new FileOutputStream(targetPath);
//获取通道
inChannel = fis.getChannel();
outChannel = fos.getChannel();
//分配指定大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
while (inChannel.read(buf) != -1) {
//转换为读取数据模式
buf.flip();
//写入到磁盘
outChannel.write(buf);
//清空缓冲区
buf.clear();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭流
try {
if (outChannel != null) {
outChannel.close();
}
if (inChannel != null) {
inChannel.close();
}
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
作者最新文章
漫蛙manwa防丢网站2026最新地址
2026-11-22 16:55
AO3官网入口 官方登录页面安全直达
2026-11-21 14:10
12306退票后手续费计算异常怎么处理
2026-11-17 11:22
Yandex外贸搜索工具 俄罗斯客户开发官网入口
2026-11-14 11:26
bilibili视频封面怎么替换已发布的
2026-11-12 11:52
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多

































