Java文件/文件夹的新增/删除/递归遍历

获取File对象

这里的字符串可以乱写,但是如果不存在后续的操作也会失败

 // 获取抽象的File对象(文件或者目录,不一定真实存在)
        File file1 = new File("D:\\2_WorkSpace\\qcbyProject\\shixun\\collection-test\\src\\FileTestPath");
        System.out.println(file1.getName());
        System.out.println(file2.getName());
        // 用exist判断文件/文件夹是否存在
        boolean file1Exist = file1.exists();
        System.out.println(file2Exist);

创建文件/文件夹

 		// 创建文件,重复创建会报错(先判断是否存在)
        boolean isFile2Create = file2.createNewFile();
        System.out.println(isFile2Create);
        boolean isFile3Create = file3.createNewFile();
        System.out.println(isFile3Create);
        // 创建文件夹,重复创建会报错(先判断是否存在)
        File path1 = new File("D:\\2_WorkSpace\\qcbyProject\\shixun\\collection-test\\src\\FileTestPath\\pathCreate");
        boolean isPath1Create = path1.mkdir();
        System.out.println(isPath1Create);

删除

 // 删除文件/目录
        File wordFile = new File("D:\\2_WorkSpace\\qcbyProject\\shixun\\collection-test\\src\\FileTestPath\\新建 Microsoft Word 文档.docx");

        boolean wordDelete = wordFile.delete();
        System.out.println(wordDelete);

递归遍历

递归遍历打印文件名/目录名

public static void printFileAllChilds(File file) {
        if (file == null || !file.exists()) {
            return;
        }
        //给层级来加一
        level++;

        if (file.isDirectory()) {
            File[] fileArr = file.listFiles();
            for (File child : fileArr) {
                printFileAllChilds(child);
            }
        } else {
            //打印层级的缩进
            for (int i = 0; i < level; i++)
                System.out.print("\t");
            System.out.println(file.getName());
        }

        //本层次遍历完毕把层级减回来
        level--;
    }

我们假设打印D盘

File fileToPrint = new File("D://");

输出结果
在这里插入图片描述

递归遍历并删除文件夹下所有的文件(不删除目录)

谨慎选择File的路径,不要选择特别大的范围,比如整个C盘或者D盘,运行此代码出现的一切后果请读者自负!!!

public static void deleteFileChilds(File file) {
        if (file == null || !file.exists()) {
            return;
        }

        if (file.isDirectory()) {
            File[] fileArr = file.listFiles();
            for (File child : fileArr) {
                deleteFileChilds(child);
            }
        } else {
            System.out.println(file.getName());
            file.delete();
        }

    }

我这里选择的File是一个很小的文件夹

File fileToDelete = new File("D:\\2_WorkSpace\\qcbyProject\\shixun\\collection-test\\src\\FileTestPath");



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值