如何通过JAVA NIO非直接缓冲区拷贝文件
作者:归人云淡风轻
时间:2023-05-04
浏览:4
通过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();
}
}
}
作者最新文章
AO3最新可用链接及中文入口汇总
2026-10-29 13:32
coreldraw怎么插入图片 图片导入步骤
2026-10-27 15:37
coreldraw快捷键冲突 怎么改 自定义按键解决
2026-10-24 08:50
AO3中文界面设置指南与核心功能使用教程
2026-10-14 23:28
解决win10运行3DMAX自动重启的方法
2026-10-13 17:08
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多

































