In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains the "java io file operation to delete files or folders", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "java io file operation to delete files or folders" bar!
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.
DeleteOnExit () Files.delete (Path path) Files.deleteIfExists (Path path) of delete () File class of File class
The differences between them:
Delete () true of File class cannot (return false) cannot (return false) deleteOnExit () void of traditional IOFile class cannot, but if it does not exist, it will not be deleted. Cannot (return void) traditional IO, this is a pit, avoid using Files.delete (Path path) voidNoSuchFileExceptionDirectoryNotEmptyExceptionNIO, the author recommends to use Files.deleteIfExists (Path path); truefalseDirectoryNotEmptyExceptionNIO from the above comparison, you can see that the traditional IO method to delete files or folders, and then delete failure, at most return a false. 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 method at this point, do better, delete success or failure has a specific return value or exception information, which is conducive to us in deleting files or folders to do a better exception handling procedures need to pay attention to the traditional IO deleteOnExit method, the author thinks 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 @ Testvoid testDeleteFileDir1 () {File file = new File ("D:\\ data\\ test"); boolean deleted = file.delete (); System.out.println (deleted);} / / void, delete failure without any hint, should avoid using this method, is a hole @ Testvoid 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@Testvoid 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@Testvoid 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 ();}
2.1. WalkFileTree and FileVisitor use the walkFileTree method to traverse the entire file directory tree, and use FileVisitor to process every file or folder traversed. The visitFile method of FileVisitor is used to deal with the "file" in the traversal result, so we can delete the postVisitDirectory method of the file FileVisitor in this method, pay attention to the "post" in the method and 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.
@ Testvoid 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 files or folders by file name. Parameter Path contains file or folder name to delete files according to file creation time, modification time, file size and other information. 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), the traversal result is a Stream to process each traversal result, just 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\ test2
2.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
Thank you for your reading, the above is the "java io file operation to delete files or folders method" of the content, after the study of this article, I believe that you have a deeper understanding of the java io file operation to delete files or folders method of this problem, the specific use of the situation also needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.