Java复制文件夹及子文件

//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]);
			}
		}
		
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java复制文件夹下的所有文件可以使用递归方法来实现。具体步骤如下: 1. 创建一个方法,传入源文件夹和目标文件夹的路径作为参数。 2. 使用File类的listFiles()方法获取源文件夹下的所有文件文件夹。 3. 遍历源文件夹下的每个文件文件夹。 4. 对于文件,使用File类的字节输入流(FileInputStream)和字节输出流(FileOutputStream)来进行复制操作。首先创建输入流读取源文件内容,再创建输出流将内容写入目标文件中。 5. 对于文件夹,递归调用该方法,将文件夹作为源文件夹、目标文件夹路径作为参数传入。 6. 复制完成后,关闭输入流和输出流。 下面是代码示例: ```java import java.io.*; public class CopyFolder { public static void main(String[] args) { String sourceFolder = "源文件夹路径"; String targetFolder = "目标文件夹路径"; copyFiles(sourceFolder, targetFolder); } public static void copyFiles(String sourceFolder, String targetFolder) { File source = new File(sourceFolder); File[] files = source.listFiles(); if (files != null) { for (File file : files) { if (file.isFile()) { File target = new File(targetFolder + File.separator + file.getName()); try (InputStream in = new FileInputStream(file); OutputStream out = new FileOutputStream(target)) { byte[] buffer = new byte[4096]; int length; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } } catch (IOException e) { e.printStackTrace(); } } else if (file.isDirectory()) { String newSourceFolder = sourceFolder + File.separator + file.getName(); String newTargetFolder = targetFolder + File.separator + file.getName(); copyFiles(newSourceFolder, newTargetFolder); } } } } } ``` 以上代码会将源文件夹下的所有文件文件夹复制到目标文件夹中。如果源文件夹有多级文件夹,也会被递归复制

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值