File类之拷贝文件

需求: 从键盘接受两个文件夹路径. 把其中一个文件夹中的内容拷贝到另一个文件夹
1.获取文件夹路径
2.把其中一个文件夹中的内容拷贝到另一个文件夹

以下为两个方法

/*
	 * 获取文件夹路径
	 * 1.返回值类型File
	 * 2.参数列表 无
	 */
	public static File getDir(){
		System.out.println("请输入文件夹路径");
		Scanner  sc = new Scanner(System.in);
		while(true){
			File file = new File(sc.nextLine());
			if(!file.exists()) {
				System.out.println("该文件夹路径不存在!重新输入");
			}else if(file.isFile()){
				System.out.println("请输入文件夹路径");
			}else{
				return file;
			}
		}
		
	}


/*
	 * 把其中一个文件夹中的内容拷贝到另一个文件夹
	 * 1.返回值类型 void
	 * 2.参数列表 File src, File dest
	 */
	public static void copy(File src, File dest) throws IOException {
		
		//1.在目标文件夹中创建原文件夹
		File newDir = new File(dest,src.getName());
		newDir.mkdir();
		//2.获取原文件夹中所有的文件和文件夹
		File[] subFiles = src.listFiles();
		//3.遍历数组
		for (File file : subFiles) {
		//4.如果是文件就用io流读写
			if(file.isFile()){
				BufferedInputStream bin = new BufferedInputStream(new FileInputStream(file));
				BufferedOutputStream bout = 
						new BufferedOutputStream(new FileOutputStream(new File(newDir,file.getName())));
				int len;
				while((len = bin.read())!= -1){
					bout.write(len);
				}
				bin.close();
				bout.close();
			}else{
				//5.如果是文件夹就递归调用
				copy(file, newDir);
			}
		}
	}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值