IO流根据键盘输入一个目录,拷贝到指定的目录中

IO流根据键盘输入一个目录,拷贝到指定的目录中

			package work;

import org.junit.Test;
import unilt.IOunilt;

import java.io.*;
import java.util.Scanner;

/**
 *  //根据键盘输入一个目录,拷贝到指定的目录中
 */
public class Demo01 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个目录");
        String num = sc.next();
        System.out.println("请输入到指定的目录");
        String num1 = sc.next();
        //如果目录不存在,创建一个目录
       cp(num,num1);
    }

    public static void cp(String str,String srr){//str是输入的目录,srr是指定的目录
        //输入的目录
        File f1 = new File(str);
        //指定的目录
        File f2;
        //获取目录下的子目录和文件
        File[] f = f1.listFiles();
        //在指定目录下拼接下级目录
        srr = srr+"\\"+f1.getName();
        //拼接的目录传给f2
        f2 = new File(srr);
        f2.mkdirs();
        for (int i = 0; i < f.length; i++) {
            if (f[i].isDirectory()){
                cp(f[i].getAbsolutePath(),srr);//使用递归相对路径
            }else {
                srr = srr+"\\"+f1.getName();
                f2 = new File(srr);
                copyFile(f[i],f2);
            }
        }
    }
    /**
     *
     * @param f1
     * @param f2
     * @throws Exception
     */
    public static void copyFile(File f1,File f2){
        BufferedInputStream bi = null;
        BufferedOutputStream bd = null;
        try {
            bi = new BufferedInputStream(new FileInputStream(f1));
            bd = new BufferedOutputStream(new FileOutputStream(f2));
            byte[] b = new byte[1024];
            int len;
            while ((len = bi.read(b)) != -1){
                bd.write(b,0,len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            IOunilt.closeAll(bi,bd);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值