java 遍历目录 删除目录 判断是否为目录

删除目录

    private static boolean deleteDir(File file) {
        if (file == null || !file.exists()) {
            System.out.println("delete files fail, file doesn't exist.");
            return false;
        }
        if (file.isFile()) {
            return file.delete();
        }
        try (Stream<Path> walk = Files.walk(file.toPath())) {
            walk.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(curFile -> {
                System.out.println("path:" + curFile.getAbsolutePath());
                curFile.delete();
            });
        } catch (SecurityException ex) {
            System.out.println("exception while delete files." + ex.getMessage());
            return false;
        } catch (IOException ex) {
            System.out.println("exception while delete files, io exception." + ex.getMessage());
            return false;
        }
        if (file.exists()) {
            return false;
        }

        System.out.println("delete success.");
        return true;
    }

 

判断目录是否为空

        if(file.isDirectory()){
            if(file.list().length>0){
                System.out.println("目录不为空!");
            }else{
                System.out.println("目录为空!");
            }
        }else{
            System.out.println("这不是一个目录!");
        }
    }

 

遍历目录

Files.walk(file.toPath()).map(Path::getFileName).forEach(System.out::println);

 

posted @ 2022-09-30 15:03  SaraMorning  阅读(188)  评论(0编辑  收藏  举报