自学内容网 自学内容网

Java-I/O框架13:文件夹的递归遍历和递归删除

视频链接:16.29 递归遍历和递归删除_哔哩哔哩_bilibiliicon-default.png?t=O83Ahttps://www.bilibili.com/video/BV1Tz4y1X7H7?spm_id_from=333.788.videopod.episodes&vd_source=b5775c3a4ea16a5306db9c7c1c1486b5&p=29

1.文件夹的递归遍历

public class ListDirectoryDemo01 {
    public static void main(String[] args) {
        listDirectory(new File("C:\\qqq"));
    }
    public static void listDirectory(File directory){
        System.out.println(directory.getAbsoluteFile());
        File[] files = directory.listFiles();
        if (files!=null){
            for (File file : files) {
                if (file.isDirectory()){
                    listDirectory(file);//递归操作
                }else {
                    System.out.println(file.getAbsoluteFile());
                }
            }
        }
    }
}

2.文件夹的递归删除

//案例2:递归删除文件夹
public class ListDirectoryDemo01 {
    public static void main(String[] args) {
        deleteDirectory(new File("C:\\qqq"));
    }
    public static void deleteDirectory(File directory){
        File[] files = directory.listFiles();
        if (files!=null){
            for (File file : files){
                if (file.isDirectory()){
                    deleteDirectory(file);//递归操作
                }else {
                    System.out.println("删除: " + file.getAbsoluteFile() +"  " + file.delete());
                }
            }
        }
        System.out.println("删除: " + directory.getAbsoluteFile() + "  " + directory.delete());
    }
}


原文地址:https://blog.csdn.net/zhangjinajian759/article/details/143636373

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!