J2SE学习笔记:递归拷贝文件夹

package cn.itcast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Scanner;


public class CopyDemo {
	public static void main(String[] args){
		//String src = "G:\\temp";			将这两个字符串改由Scanner接收
		//String dest = "F:";
		Scanner sc = new Scanner(System.in);
		
		System.out.println("请输入需要被拷贝的文件夹的路径(路径中斜杠请使用双斜杠):");
		String src = sc.next();
		System.out.println("请输入拷贝目标位置:");
		String dest = sc.next();
		File srcfile = new  File(src);
		File destfile = new  File(dest);
		try{
			copy(srcfile,destfile);
		}catch(Exception e){
			throw new RuntimeException("拷贝文件失败,请检查源文件或者目标位置是否存在");
		}
		System.out.println("拷贝完毕,请查看。");
			
			
	}
		
		public static void copy(File srcfile,File destfile) throws Exception{
			//在目标位置创建同名文件夹
			File newDir = new File(destfile,srcfile.getName());
			newDir.mkdir();
			//遍历源文件夹
			File[] subFiles = srcfile.listFiles();
			for (File subfile : subFiles) {	
				 // 输出文件名,测试文件是否遍历成功
				String name = subfile.getName();
				System.out.println(name);
				//如果是文件,直接拷贝
				if(subfile.isFile()){
					FileInputStream fileInputStream = new FileInputStream(subfile);
					FileOutputStream fileOutputStream = new FileOutputStream(new File(newDir,subfile.getName()));
					
					int i = 0;
					byte [] arr = new byte[1024];
					while((i = fileInputStream.read(arr)) != -1){
						fileOutputStream.write(arr,0,i);
						fileOutputStream.flush();
					}
					fileInputStream.close();
					fileOutputStream.close();
					//如果不是文件夹,递归调用拷贝方法
				}else{
					copy(subfile,newDir);			
				}
	
			}
			
		}
	}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值