What are the methods to delete files or folders in Java?
Four basic methods to delete files or folders
The following four methods can all delete files or folders.
What they have in common is:
Deletion will fail when the folder contains sub-files, which means that these four methods can only delete empty folders.
//delete is to perform deletion immediately, while deleteOnExit is to delete the program when it exits the virtual machine.
delete() of File class
deleteOnExit() of File class
: When the virtual machine terminates, delete The file or directory represented by the File object. If it represents a directory, you need to ensure that the directory is empty, otherwise it cannot be deleted and there is no return value.Files.delete(Path path)
: Delete files located on the path passed as parameter. For other file system operations, this method may not be atomic. If the file is a symbolic link, the symbolic link itself will be deleted rather than the final target of the link. If the file is a directory, this method only deletes the file if the directory is empty.
Files.deleteIfExists(Path path)
It should be noted that:
The File class in traditional IO and the Path class in NIO can represent both files and folder.
A simple comparison of the above four methods
- | Explanation | Successful return value | Whether it can be judged that the folder does not exist and causes failure | Whether it can be judged that the folder is not empty and causes failure |
---|---|---|---|---|
delete( of File class ) | Traditional IO | true | Cannot (return false) | Cannot (return false) |
Traditional IO, this is a pitfall, avoid using | void | It cannot be used, but if it does not exist, the deletion will not be performed | Cannot (return void) | |
NIO, it is recommended to use | void | NoSuchFileException | DirectoryNotEmptyException | |
NIO | true | false | DirectoryNotEmptyException |
//删除暂存的pdf File file =new File(pdfFilename); file.delete(); Path path3 = Paths.get(pdfFilename); Files.delete(path3);
Difference:
-File.delete() | Files.delete(Path path) | |
---|---|---|
JDK1.0 | JDK1.7 | |
Instance method of java.io.File object | Static method of java.nio.file.Files class | |
No parameters | java.nio.file.Path | |
boolean | void | ##Exception declaration |
Statement to throw java.io.IOException | The file does not exist | |
Throw java.nio. file.NoSuchFileException | Delete non-empty directory | |
Cannot delete, throw java.nio.file.DirectoryNotEmptyException | Delete occupied files | |
Cannot be deleted, throw java.nio.file.FileSystemException | The file cannot be deleted for other reasons | |
Throw the specific subclass of java.io.IOException | ##如何删除整个目录或者目录中的部分文件先造数据 private void createMoreFiles() throws IOException { Files.createDirectories(Paths.get("D:\data\test1\test2\test3\test4\test5\")); Files.write(Paths.get("D:\data\test1\test2\test2.log"), "hello".getBytes()); Files.write(Paths.get("D:\data\test1\test2\test3\test3.log"), "hello".getBytes()); } Copy after login walkFileTree与FileVisitor使用walkFileTree方法遍历整个文件目录树,使用FileVisitor处理遍历出来的每一项文件或文件夹
在去删除文件夹之前,该文件夹里面的文件已经被删除了。 @Test void testDeleteFileDir5() throws IOException { createMoreFiles(); Path path = Paths.get("D:\data\test1\test2"); Files.walkFileTree(path, new SimpleFileVisitor<Path>() { // 先去遍历删除文件 @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); System.out.printf("文件被删除 : %s%n", file); return FileVisitResult.CONTINUE; } // 再去遍历删除目录 @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); System.out.printf("文件夹被删除: %s%n", dir); return FileVisitResult.CONTINUE; } } ); } Copy after login 下面的输出体现了文件的删除顺序
我们既然可以遍历出文件夹或者文件,我们就可以在处理的过程中进行过滤。比如: 按文件名删除文件或文件夹,参数Path里面含有文件或文件夹名称 按文件创建时间、修改时间、文件大小等信息去删除文件,参数BasicFileAttributes 里面包含了这些文件信息。 Files.walk如果你对Stream流语法不太熟悉的话,这种方法稍微难理解一点,但是说实话也非常简单。 使用Files.walk遍历文件夹(包含子文件夹及子其文件),遍历结果是一个Stream 对每一个遍历出来的结果进行处理,调用Files.delete就可以了。 @Test void testDeleteFileDir6() throws IOException { createMoreFiles(); Path path = Paths.get("D:\data\test1\test2"); try (Stream<Path> walk = Files.walk(path)) { walk.sorted(Comparator.reverseOrder()) .forEach(DeleteFileDir::deleteDirectoryStream); } } private static void deleteDirectoryStream(Path path) { try { Files.delete(path); System.out.printf("删除文件成功:%s%n",path.toString()); } catch (IOException e) { System.err.printf("无法删除的路径 %s%n%s", path, e); } } Copy after login 问题:怎么能做到先去删除文件,再去删除文件夹? 利用的是字符串的排序规则,从字符串排序规则上讲,“D:\data\test1\test2”一定排在“D:\data\test1\test2\test2.log”的前面。 所以我们使用“sorted(Comparator.reverseOrder())”把Stream顺序颠倒一下,就达到了先删除文件,再删除文件夹的目的。 下面的输出,是最终执行结果的删除顺序。
传统IO-递归遍历删除文件夹传统的通过递归去删除文件或文件夹的方法就比较经典了 //传统IO递归删除 @Test void testDeleteFileDir7() throws IOException { createMoreFiles(); File file = new File("D:\data\test1\test2"); deleteDirectoryLegacyIO(file); } private void deleteDirectoryLegacyIO(File file) { File[] list = file.listFiles(); //无法做到list多层文件夹数据 if (list != null) { for (File temp : list) { //先去递归删除子文件夹及子文件 deleteDirectoryLegacyIO(temp); //注意这里是递归调用 } } if (file.delete()) { //再删除自己本身的文件夹 System.out.printf("删除成功 : %s%n", file); } else { System.err.printf("删除失败 : %s%n", file); } } Copy after login 需要注意的是: listFiles()方法只能列出文件夹下面的一层文件或文件夹,不能列出子文件夹及其子文件。 先去递归删除子文件夹,再去删除文件夹自己本身。 The above is the detailed content of What are the methods to delete files or folders in Java?. For more information, please follow other related articles on the PHP Chinese website! Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
![]() Hot AI Tools![]() Undresser.AI UndressAI-powered app for creating realistic nude photos ![]() AI Clothes RemoverOnline AI tool for removing clothes from photos. ![]() Undress AI ToolUndress images for free ![]() Clothoff.ioAI clothes remover ![]() AI Hentai GeneratorGenerate AI Hentai for free. ![]() Hot Article
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
How Long Does It Take To Beat Split Fiction?
3 weeks ago
By DDD
R.E.P.O. Save File Location: Where Is It & How to Protect It?
3 weeks ago
By DDD
![]() Hot Tools![]() Notepad++7.3.1Easy-to-use and free code editor ![]() SublimeText3 Chinese versionChinese version, very easy to use ![]() Zend Studio 13.0.1Powerful PHP integrated development environment ![]() Dreamweaver CS6Visual web development tools ![]() SublimeText3 Mac versionGod-level code editing software (SublimeText3) ![]() Hot Topics![]() Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively. ![]() Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation. ![]() Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples. ![]() Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples. ![]() Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code. ![]() Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation. ![]() In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview. ![]() Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is ![]() |