Java复制文件夹及子文件

本文介绍了一种文件及文件夹复制的方法,适用于小文件的快速复制,通过一次性读取整个文件到内存中并写入目标位置,简化了循环读写的复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//COPY 文件及文件夹,整个一下子读取,不用while---对小文件试用,内存缓冲压力较小

private void copy(String srcpath,String decpath) throws Exception {
		File file = new File(srcpath);
		File file2 = new File(decpath);
		
		if(file.isFile()){
			
			FileInputStream fis = new FileInputStream(file);
			FileOutputStream fot = new FileOutputStream(file2);
			byte[] by = new byte[(int)file.length()];
			int a = 0;
			//while( (a = fis.read(by)) != -1){
			//	fot.write(by, 0, a);
                            //注意不能 fot.write(by) 会造成新文件比老文件大,不是每个都正好by大小 
			//}
			fis.read(by);
			fot.write(by);
			fis.close();
			fot.flush();
			fot.close();
		}else if(file.isDirectory()){
			file2.mkdirs();
			
			String[] files = file.list();
			for(int i = 0 ;i < files.length ; i++){
				copy(srcpath+"\\"+files[i],decpath+"\\"+files[i]);
			}
		}
		
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值