Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the method for JAVA to delete a file or folder

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

The main content of this article is to explain "what is the method of deleting files or folders by JAVA". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what is the method of deleting files or folders by JAVA"?

I. four basic methods for deleting files or folders

The following four methods can delete files or folders, and what they have in common is that deletion fails when the folder contains subfiles, which means that these four methods can only delete empty folders.

It is important to note that the File class in traditional IO and the Path class in NIO can represent both files and folders.

Delete () of the File class

DeleteOnExit () of the File class

Files.delete (Path path)

Files.deleteIfExists (Path path)

The differences between them:

Whether the successful return value can distinguish whether the folder does not exist and cause the failure to fail. If the folder is not empty, the delete () true of the File class cannot (return false) cannot (return false) the deleteOnExit () void of the traditional IOFile class cannot, but if it does not exist, it cannot be deleted and cannot (return void) the traditional IO, this is a pit, avoid using Files.delete (Path path) voidNoSuchFileExceptionDirectoryNotEmptyExceptionNIO, the author recommends to use Files.deleteIfExists (Path path);

As can be seen from the above comparison, when the traditional IO method deletes a file or folder and then fails to delete it, a maximum of one false is returned. The specific reason for the deletion failure cannot be discovered through this false, because the deletion failure does not exist in the file itself. Or is the deletion failed because the folder is not empty?

NIO's method does better at this point. Both successful and unsuccessful deletions have specific return values or exception information, which helps us to better handle program exceptions when deleting files or folders.

What needs to be noticed is the deleteOnExit method in traditional IO, and the author thinks that we should avoid using it. It will always only return void, delete failure will not have any Exception thrown, so I recommend not to use, lest you delete failure when there is no response, and you may mistakenly think that the deletion was successful.

/ / false can only tell you that you failed, but did not give any reason for the failure [@ Test] (https://my.oschina.net/azibug)void testDeleteFileDir1 () {File file = new File ("D:\ data\\ test"); boolean deleted = file.delete (); System.out.println (deleted) } / / void, the deletion failed without any hint, so you should avoid using this method. It is just a pit [@ Test] (https://my.oschina.net/azibug)void testDeleteFileDir2 () {File file = new File ("D:\\ data\\ test1"); file.deleteOnExit () } / / if the file does not exist, throw NoSuchFileException//. If the folder contains files, throw DirectoryNotEmptyException [@ Test] (https://my.oschina.net/azibug)void testDeleteFileDir3 () throws IOException {Path path = Paths.get ("D:\\ data\\ test1"); Files.delete (path) / / return value void} / / if the file does not exist, return false, indicating deletion failed (file does not exist) / / if the folder contains files, throw DirectoryNotEmptyException [@ Test] (https://my.oschina.net/azibug)void testDeleteFileDir4 () throws IOException {Path path = Paths.get ("D:\\ data\\ test1"); boolean result = Files.deleteIfExists (path); System.out.println (result);}

In the final analysis, it is recommended that you use java NIO's Files.delete (Path path) and Files.deleteIfExists (Path path) to delete files or folders.

How to delete the whole directory or some files in the directory

As mentioned above, when the four API delete folders, if the folder contains child files, the deletion will fail. So, what if we do want to delete the entire folder?

Prerequisite preparation

To make it easier for us to experiment later, let's first create a directory structure where ".log" ends with data files and the rest is a folder.

You can use the code of the substitute face to create

Private void createMoreFiles () throws IOException {Files.createDirectories ("D:\\ data\\ test1\\ test2\\ test3\\ test4\\ test5\"); Files.write ("D:\\ data\\ test1\\ test2\ test2.log"), "hello" .getBytes (); Files.write ("D:\\ data\\ test1\ test2\\ test3\ test3.log"), "hello" .getBytes ()) WalkFileTree and FileVisitor

Use the walkFileTree method to traverse the entire file directory tree, and use FileVisitor to process each traversed file or folder

FileVisitor's visitFile method is used to process the "file" in the traversal result, so we can delete the file in this method.

The postVisitDirectory method of FileVisitor, notice that the "post" in the method means "do it later." So it is used to deal with the folder after all the files have been processed, so using this method to delete the folder can effectively avoid the exception that the content of the folder is not empty, because before deleting the folder, the files in the folder have been deleted.

[@ Test] (https://my.oschina.net/azibug)void testDeleteFileDir5 () throws IOException {createMoreFiles (); Path path = Paths.get ("D:\\ data\\ test1\ test2") Files.walkFileTree (path, new SimpleFileVisitor () {/ / first traverse the deleted file @ Override public FileVisitResult visitFile (Path file, BasicFileAttributes attrs) throws IOException {Files.delete (file); System.out.printf ("File deleted:% s% n", file); return FileVisitResult.CONTINUE } / / then traverse the delete directory @ Override public FileVisitResult postVisitDirectory (Path dir, IOException exc) throws IOException {Files.delete (dir); System.out.printf ("folder deleted:% s% n", dir); return FileVisitResult.CONTINUE });}

The following output reflects the order in which the files are deleted

File deleted: d:\ data\ test1\ test2\ test2.log file deleted: d:\ data\ test1\ test2\ test3\ test3.log folder deleted: d:\ data\ test1\ test2\ test3\ test4\ test5 folder deleted: d:\ data\ test1\ test2\ test3\ test4 folder deleted: d:\ data\ test1\ test2\ test3 folder deleted: d:\ data\ test1\ test2

Now that we can traverse folders or files, we can filter them in the process. For example:

Delete a file or folder by file name. The parameter Path contains the file or folder name.

Delete the file according to the file creation time, modification time, file size and other information. The parameter BasicFileAttributes contains these file information.

2.2.Files.walk

This approach is a little harder to understand if you are not familiar with the Stream stream syntax, but to be honest, it is also very simple.

Use Files.walk to traverse folders (including subfolders and their files), and the result is a Stream

To process each traversed result, call Files.delete.

@ Testvoid testDeleteFileDir6 () throws IOException {createMoreFiles (); Path path = Paths.get ("D:\ data\\ test1\\ test2"); try (Stream walk = Files.walk (path)) {walk.sorted (Comparator.reverseOrder ()) .forEach (DeleteFileDir::deleteDirectoryStream);} private static void deleteDirectoryStream (Path path) {try {Files.delete (path) System.out.printf ("delete file successfully:% s% n", path.toString ());} catch (IOException e) {System.err.printf ("path% s%n%s", path, e);}}

Question: how can you delete a file before deleting a folder? . Using string collation, "D:\ data\ test1\ test2" must precede "D:\ data\ test1\ test2\ test2.log" in terms of string sorting. So we use "sorted (Comparator.reverseOrder ())" to reverse the order of Stream, thus achieving the goal of deleting files first and then deleting folders.

The following output is the deletion order of the final execution result.

File deleted successfully: d:\ data\ test1\ test2\ test3\ test4\ test5 deleted file successfully: d:\ data\ test1\ test2\ test3\ test4 deleted file successfully: d:\ data\ test1\ test2\ test3\ test3.log deleted file successfully: d:\ data\ test1\ test2\ test3 deleted file successfully: d:\ data\ test1\ test2\ test2.log deleted file successfully: d:\ data\ test1\ test22.3. Traditional IO- recursively traverses deleted folders

The traditional method of deleting files or folders by recursion is more classic.

/ / traditional IO recursively deletes @ Testvoid testDeleteFileDir7 () throws IOException {createMoreFiles (); File file = new File ("D:\\ data\\ test1\\ test2"); deleteDirectoryLegacyIO (file);} private void deleteDirectoryLegacyIO (File file) {File [] list = file.listFiles () / / unable to achieve list multi-tier folder data if (list! = null) {for (File temp: list) {/ / delete subfolders and subfiles deleteDirectoryLegacyIO (temp) first / / Note here is a recursive call}} if (file.delete ()) {/ / then delete your own folder System.out.printf ("delete success:% s% n", file);} else {System.err.printf ("delete failed:% s% n", file);}}

It is important to note that:

The listFiles () method lists only one layer of files or folders below the folder, not subfolders and their subfiles.

First delete the subfolder recursively, and then delete the folder itself

At this point, I believe you have a deeper understanding of "what is the method of deleting files or folders by JAVA". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report