利用File类和IO流将一个文件夹的所有内容拷贝到另一个文件夹下

class hello {

	public static void main(String[] args) throws IOException {
		File one = Dir();
		File two = Dir();
		if(one.equals(two)) {
				System.out.println("目标文件是源文件夹的子文件夹");
			}else {
				Copy(one,two);
			}
		
	}

	public static void Copy(File one , File two) throws IOException {
		File toDir = new File(two,one.getName());//获取目标文件夹的目录
		
		toDir.mkdir();//在目标文件夹目录下新建与源文件夹相同名字的文件夹
		File[] files = one.listFiles();
		for (File file : files) {
			if(file.isFile()) {
				BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
				BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(toDir,file.getName())));
				int a;
				if((a = bis.read()) != -1){
					bos.write(a);
				}
				bis.close();
				bos.close();
			}else {
				Copy(file, toDir);
			}
		}
	}
	
	public static File Dir() {//获取文件夹路径方法
		System.out.println("请输入文件夹路径:");
		Scanner sc = new Scanner(System.in);
		String line = sc.nextLine();
		File dir = new File(line);
		while (true) {
			if (!dir.exists()) {
				System.out.println("路径不存在,请重新输入: ");
			} else if (dir.isFile()) {
				System.out.println("请重新输入一个文件夹路径");
			} else {
				return dir;
			}
		}
	}

源文件夹:

 

运行结果:

复制后目标文件夹:

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用Java的文件操作(File)和输入输出(IO)来实现这个功能。具体步骤如下: 1. 创建文件夹目标文件夹File对象,例如: ``` File srcFolder = new File("C:\\sourceFolder"); File destFolder = new File("D:\\destinationFolder"); ``` 2. 检查文件夹是否存在,目标文件夹是否不存在,如果目标文件夹不存在则创建目标文件夹,例如: ``` if (srcFolder.exists() && !destFolder.exists()) { destFolder.mkdir(); } ``` 3. 获取文件夹下所有文件夹File对象,例如: ``` File[] subFolders = srcFolder.listFiles(File::isDirectory); ``` 4. 遍历所有文件夹,将每个文件夹拷贝目标文件夹下,例如: ``` for (File subFolder : subFolders) { File destSubFolder = new File(destFolder, subFolder.getName()); copyFolder(subFolder, destSubFolder); } ``` 其中,copyFolder()方法是自定义的递归方法,用于将一个文件夹及其文件夹拷贝目标文件夹下,例如: ``` private static void copyFolder(File srcFolder, File destFolder) { if (srcFolder.isDirectory()) { if (!destFolder.exists()) { destFolder.mkdir(); } String[] files = srcFolder.list(); for (String file : files) { File srcFile = new File(srcFolder, file); File destFile = new File(destFolder, file); copyFolder(srcFile, destFile); } } else { try (InputStream in = new FileInputStream(srcFolder); OutputStream out = new FileOutputStream(destFolder)) { byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } } catch (IOException e) { e.printStackTrace(); } } } ``` 这样,就可以将文件夹下所有文件夹拷贝目标文件夹下了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值