java删除目录及文件

java nio删除目录及文件非递归方式

    /**
     * 删除目录
     * @param rootDir 目录
     */
    public static void deleteDir(String rootDir) throws IOException {
        Files.walkFileTree(Paths.get(rootDir), new FileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.deleteIfExists(Paths.get(file.getParent() + File.separator + file.getFileName()));
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                // 删除目录
                Files.deleteIfExists(dir);
                return FileVisitResult.CONTINUE;
            }
        });
    }
posted @ 2021-07-25 22:33  学无终  阅读(287)  评论(0编辑  收藏  举报