从控制台获取输入的文件目录然后将该目录(包含子目录)下的.java文件复制到D:/java文件夹中,并统计java文件的个数.

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录


public class Test {
    public static void main(String[] args) throws IOException {
        Scanner sc=new Scanner(System.in);
        System.out.println("输入源文件夹路径:");
        String source=sc.next();
        System.out.println("输入目标文件夹路径:");
        String targetDirk=sc.next();
        int count=dirkCopyFile(source,targetDirk,"java");
        System.out.println("java文件的个数为:"+count);
    }

    //复制文件的函数
    public static void copy(String source,String target) throws IOException {
        BufferedInputStream bis=new BufferedInputStream(new FileInputStream(source));
        BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(target));
        byte[] b=new byte[1024];
        int len=0;
        while ((len=bis.read(b))!=-1){
            bos.write(b,0,len);
            bos.flush();
        }
        bos.close();
        bis.close();
    }
    //将source下的type类型文件复制到targetDirk下
    public static int  dirkCopyFile(String source,String targetDirk,String type) throws IOException {
        int count=0;
        File file=new File(source);
        //如果file是文件就进行复制
        if (file.isFile()){
            //产生一个目标路径,文件名引用原文件的文件名
            File newFile=new File(targetDirk+"\\"+file.getName());
            //获取最后一个".",准备截取后缀名。
            int index=file.getName().lastIndexOf(".");
            //如果是type类型的文件,就进行复制
            if(file.getName().substring(index+1).equals(type)) {
                //如果targetDirk文件夹下有同名的文件,就修改文件名(目前源文件夹中只有一个同名文件,如果有多个会覆盖)
                if (!newFile.exists()) {
                    copy(file.getAbsolutePath(), targetDirk + "\\" + file.getName());
                    return 1;
                } else {
                    copy(file.getAbsolutePath(), targetDirk + "\\" + file.getName() + "(1)");
                    return 1;
                }
            }
            //如果是文件夹就进入下一层文件夹
        }else if (file.isDirectory()){
            File[] files=file.listFiles();
            if (files.length!=0){
                for (File f:files){
                    count+=dirkCopyFile(f.getAbsolutePath(),targetDirk,type);
                }
            }
        }

        return count;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值