java实现文件或文件夹的拷贝

本文详细介绍使用递归方法及Commons-IO库实现文件夹拷贝的过程,对比两种方式的效率,提供实用代码示例。

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

首先自己动手使用递归实现文件夹的拷贝,接着使用Commons-IO实现同样的效果

//import org.apache.commons.io.FileUtils;

public class FileTest {
	public static void main(String[] args) throws IOException {
		//long start = System.currentTimeMillis();
		//递归实现文件夹的拷贝
		dirCopy("src", "src2");
		//System.out.println(System.currentTimeMillis()-start);
		//start = System.currentTimeMillis();
		//Commons-IO实现文件夹拷贝
		FileUtils.copyDirectory(new File("src"), new File("src2"));
		//System.out.println(System.currentTimeMillis()-start);
		
	}

	public static void dirCopy(String srcPath, String destPath) {
		File src = new File(srcPath);
		if (!new File(destPath).exists()) {
			new File(destPath).mkdirs();
		}
		for (File s : src.listFiles()) {
			if (s.isFile()) {
				fileCopy(s.getPath(), destPath + File.separator + s.getName());
			} else {
				dirCopy(s.getPath(), destPath + File.separator + s.getName());
			}
		}
	}

	public static void fileCopy(String srcPath, String destPath) {
		File src = new File(srcPath);
		File dest = new File(destPath);
		//使用jdk1.7 try-with-resource 释放资源,并添加了缓存流
		try(InputStream is = new BufferedInputStream(new FileInputStream(src));
				OutputStream out =new BufferedOutputStream(new FileOutputStream(dest))) {
			byte[] flush = new byte[1024];
			int len = -1;
			while ((len = is.read(flush)) != -1) {
				out.write(flush, 0, len);
			}
			out.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

对于Commons-IO只需去官网下载Binaries版,并将commons-io-2.6.jar和commons-io-2.6-sources.jar(源代码)引入项目中即可
windows开发环境选择commons-io-2.6-bin.zip下载
http://commons.apache.org/proper/commons-io/download_io.cgi

//导入包
import org.apache.commons.io.FileUtils;
//Commons-IO复制文件 
FileUtils.copyFile(new File("p.png"),new File("p-copy.png"));
//Commons-IO复制目录
FileUtils.copyDirectory(new File("lib"),new File("lib2"));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值