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;}});}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!