1、通过io删除文件
public static void deleteFileByIO(String filePath) {File file = new File(filePath);File[] list = file.listFiles();if (list != null) {for (File temp : list) {deleteFileByIO(temp.getAbsolutePath());}}file.delete();}
2、通过Files.walk删除文件
public static void deleteFileByStream(String filePath) throws IOException {Path path = Paths.get(filePath);try (Stream<Path> walk = Files.walk(path)) {walk.sorted(Comparator.reverseOrder()).forEach(FileUtil::deleteDirectoryStream);}}private static void deleteDirectoryStream(Path path) {try {Files.delete(path);} catch (IOException e) {e.printStackTrace();}}
3、通过 Files.walkFileTree删除文件
public static void deleteFileByWalkFileTree(String filePath) throws IOException {Path path = Paths.get(filePath);Files.walkFileTree(path,new SimpleFileVisitor<Path>() {@Overridepublic FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {Files.delete(file);System.out.printf("文件被删除 : %s%n", file);return FileVisitResult.CONTINUE;}@Overridepublic FileVisitResult postVisitDirectory(Path dir,IOException exc) throws IOException {Files.delete(dir);System.out.printf("文件夹被删除: %s%n", dir);return FileVisitResult.CONTINUE;}});}