NIO 使用FileChannel完成文件复制的实战案例

下面是一个简单的实战案例:使用FileChannel复制文件。具体的功

能是使用 FileChannel 将原文件复制一份,把原文件中的数据都复制到目
标文件中
package com.crazymakercircle.iodemo.fileDemos; 
//省略import,具体请参见源代码工程 
public class FileNIOCopyDemo { 
public static void main(String[] args) { 
//演示复制资源文件 
nioCopyResouceFile(); 
}
/*** 复制两个资源目录下的文件 */ 
public static void nioCopyResouceFile() { 
//源
String sourcePath = NioDemoConfig.FILE_RESOURCE_SRC_PATH; 
String srcPath = IOUtil.getResourcePath(sourcePath);
Logger.info("srcPath=" + srcPath); 
//目标 
String destPath = NioDemoConfig.FILE_RESOURCE_DEST_PATH; 
String destDecodePath = IOUtil.builderResourcePath(destPath); Logger.info("destDecodePath=" + destDecodePath); 
//复制文件
nioCopyFile(srcDecodePath, destDecodePath); 
}
/*** NIO方式复制文件 * @param srcPath 源路径 * @param destPath目标路径 */
public static void nioCopyFile(String srcPath, String destPath){ 
File srcFile = new File(srcPath); 
File destFile = new File(destPath); 
try {
    //如果目标文件不存在,则新建 
if (!destFile.exists()) { 
destFile.createNewFile(); 
}l
ong startTime = System.currentTimeMillis(); 
FileInputStream fis = null; 
FileOutputStream fos = null; 
FileChannel inChannel = null; //输入通道
FileChannel outchannel = null; //输出通道 
try {fis = new FileInputStream(srcFile); 
fos = new FileOutputStream(destFile); 
inChannel = fis.getChannel(); 
outchannel = fos.getChannel(); 
int length = -1; 
//新建buf,处于写模式 
ByteBufferbuf = ByteBuffer.allocate(1024); 
//从输入通道读取到buf 
while ((length = inChannel.read(buf)) != -1) { 
//buf第一次模式切换:翻转buf,从写模式变成读模式 
buf.flip(); 
int outlength = 0; 
//将buf写入输出的通道 
while ((outlength = outchannel.write(buf)) != 0) { 
System.out.println("写入的字节数:" + outlength); 
}
//buf第二次模式切换:清除buf,变成写模式 
buf.clear(); 
}
//强制刷新到磁盘 
outchannel.force(true); 
} 
finally { 
//关闭所有的可关闭对象 
IOUtil.closeQuietly(outchannel); 
IOUtil.closeQuietly(fos);
IOUtil.closeQuietly(inChannel); 
IOUtil.closeQuietly(fis); } 
long endTime = System.currentTimeMillis(); 
Logger.info("base复制毫秒数:" + (endTime - startTime)); 
} catch (IOException e) { e.printStackTrace(); 
} 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值