用IO 字符流进行从键盘接收两个文件夹路径,把其中一个文件夹中(包含内容)拷贝到另一个文件夹中

package cn.day23;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class test {
	public static void main(String[] args) {
		File f = new File("D:\\1");
		String s = "D:\\2";
				
		fofile(f, s);
	}
	/*
	 * 遍历源路劲文件夹中所有文件
	 * 1.转化为File【】数组
	 * 2.遍历 
	 * 3.调用copy方法
	 */
	public static void fofile(File f,String s){
		File[] file = f.listFiles();
		for(File fi : file){
			if(fi.isDirectory()){
				new File(s+ "\\" + fi.getName()).mkdirs();
				String news = s+ "\\" + fi.getName();
				fofile(fi,news);
			  }else{
			String fs = fi.getName();
			copy(fi, s+ "\\" +fs);
		}}
	}
	/**
	 * @param args
	 * 1.从键盘接收两个文件夹路径,把其中一个文件夹中(包含内容)拷贝到另一个文件夹中
	 * copy方法
	 */
	public static void copy(File fi1,String fo1) {
		FileInputStream fi = null;
		FileOutputStream fo = null;
		try{
			fi = new FileInputStream(fi1);
			fo = new FileOutputStream(fo1);
			int len = 0;
			byte[] by = new byte[1024];
			while((len = fi.read(by)) != -1){
				fo.write(by, 0, len);
			}
		}catch(IOException ex){
			ex.printStackTrace();
			throw new RuntimeException();
		}finally{
			try{
				
				if(fo != null)
					fo.close();
			}catch(IOException exception){
				throw new RuntimeException();
			}finally{
				try {
					if(fi != null)
						fi.close();
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}
	}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值