Java IO 文件夹复制

相关博客: Java IO

理论:

1、创建复制后的目录
2、创建文件

代码

public class FolderCopy {
	
	private static String sourceStr = "E:\\apache-tomcat-9.0.10\\apache-tomcat-9.0.10";
	private static String aimStr = "E:\\hehe";

	public static void main(String[] args) {
		File aim = new File(aimStr);
		if (!aim.exists()) {
			aim.mkdirs();
		}
		fun(new File(sourceStr), aim);
	}
	
	public static void fileCopy(File sources, File aim) {// psvm
		try (FileInputStream fis = new FileInputStream(sources); 
		     FileOutputStream fos = new FileOutputStream(aim);) {
			byte[] buf = new byte[256];
			int len = -1;
			while ((len = fis.read(buf)) != -1) {
				fos.write(buf, 0, len);
			}
		} catch (Exception e) {
		}
	}

	public static void fun(File file, File aim) {
		File[] files = file.listFiles();
		for (File item : files) {
			if (item.isFile()) {// 如果是文件,复制文件
				File source = item.getAbsoluteFile();
				String replace = item.getAbsolutePath().replace(sourceStr, aimStr);
				// 文件具体复制
				fileCopy(source, new File(replace));
			} else {// 如果是目录,创建路径
				String path = aim.getAbsolutePath() + "\\" + item.getName();
				File p = new File(path);
				if (!p.exists()) {
					p.mkdirs();
				}
				fun(item, p); //递归 
			}
		}
	}

}
发布了253 篇原创文章 · 获赞 666 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/lianghecai52171314/article/details/103806613