How do I delete multiple files in a directory in Java?
You can delete files, directories or links. With symbolic links, the link is deleted and not the target of the link. With directories, the directory must be empty, or the deletion fails. Show
The The method deletes the file or throws an exception if the deletion fails. For example, if the file does not exist a try { Files.delete(path); } catch (NoSuchFileException x) { System.err.format("%s: no such" + " file or directory%n", path); } catch (DirectoryNotEmptyException x) { System.err.format("%s not empty%n", path); } catch (IOException x) { // File permission problems are caught here. System.err.println(x); } The method also deletes the file, but if the file does not exist, no exception is thrown. Failing silently is useful when you have multiple threads deleting files and you don't want to throw an exception just because one thread did so first. Previous articles in this series have covered reading files with Java, writing files, and constructing directory and file paths with the 9 and 0 classes. This fourth part describes the most important directory and file operations. It answers the following questions:
The article answers all questions using the NIO.2 File API, introduced in Java 7 with JSR 203. Directory operationsFor the following directory operations, you need a Path-object representing the directory. You can construct this object using the static method 1 (or, before Java 11, using 2). A comprehensive tutorial on constructing directory paths with 0, 4, and 9 can be found in the third part of this series. How to list directory contents with Files.list()The easiest way to list the complete contents of a directory is the 6 method. It returns a Stream of 0 objects, which we simply write to 8 in the following example:
How to search a directory recursively with Files.list()Let's move on to a more complex case. In the following example, we want to output all regular files located in the home directory or a subdirectory of any depth thereof and whose name starts with "settings".
You can use the methods 9 and 0 to check if a file is a regular file or directory. Another file type is the symbolic link – you can recognize it with 1. It is also possible that all three methods return 2, in which case the file is of type "other" (what exactly this could be is unspecified). In the example above, we have to catch 3 inside the lambda and wrap it with an 4 because the 5 consumer of the stream must not throw a checked exception. How to search a directory recursively with Files.walk()You can write the previous example much shorter and more elegant – using 6:
However, this variant has the disadvantage that an 7 cannot be caught individually as before. If such an exception occurs here, the entire 6 method terminates. If this is acceptable for your application, this way is more beautiful than the previous one. How to search a directory recursively with Files.walkFileTree()Another variant is 9. This method implements the visitor pattern. It sends each file within the directory structure to a 0, which you pass to the method. In the following example, we use the 1 class, which implements all methods of 0. We only override the 3 method:
The method's return value, 4, indicates that 5 should continue to traverse the directory tree. Other return values would be:
The 5 variant, too, would terminate processing in the case of an 7. However, there is a way to prevent this. To do so, you also need to overwrite the method 4:
How to search a directory with Files.find()An alternative approach is the 5 method. It expects a "matcher" as the third parameter: this is a function that has a 0 and 7 as input parameters and returns a 8 indicating whether the corresponding file should be included in the result or not.
Again, an 7 would end the entire search prematurely. I don't know of any way to circumvent this with 5. If you expect subdirectories with denied access, you should either use 9 and overwrite the 2 method to catch the exception. Alternatively, use 6 and implement the recursion yourself. Accessing specific directoriesAttention: If you are using a version older than Java 11, you must replace 1 with 2 in the following code examples. Accessing the current directoryThe current directory can be found via the system property "user.dir":
Accessing the user's home directoryYou can find the home directory of the current user via the system property "user.home":
Accessing the temporary directoryAnd you can find the temporary directory via the system property "java.io.tmpdir":
If you want to create a temporary file in the temporary directory, you do not need to access the temporary directory first. There is a shortcut for this. You will find it at the beginning of the following chapter, "File operations". File operationsHow to create a temporary fileAfter the last chapter concluded with accessing the temporary directory, this one starts with a shortcut to creating temporary files:
The two parameters are a prefix and a suffix. The 6 method will insert a random number between them. When I run the method repeatedly on my Windows system and print the variable 7 to the console, I get the following output: 0 On Linux it looks like this: 1 It is essential to know that 6 does not only create the respective 0 object but actually creates an empty file. How to move a file in JavaTo move a file, use the method 0. The following example creates a temporary file and moves it to the home directory of the logged-on user: 2 The second parameter of the 1 method must represent the target file, not the target directory! If you invoked 2 here, you would get a 3. Therefore, in the example, we use the 4 method to concatenate the 5 with the name of the file to be copied. How to move a directory including all subdirectoriesYou can move a directory just like a file. In the following example, we create two temporary directories and one file in the first directory. We then move the first directory into the second: 3 How to rename file with JavaAfter all, renaming a file (or a directory) is a special case of moving, with the destination directory being the same as the source directory and only the file name changing. In the following example, we rename a temporary file to "happycoders.tmp": 4 Invoking 6 is a shortcut for 7: The directory is extracted from the source file and concatenated with the new file name. How to copy a file in JavaCopying a file is similar to renaming it. The following example copies a temporary file to the home directory: 5 This method has a significant advantage over proprietary implementations with 8 and 9, as they were necessary before Java 7 and the NIO.2 File API: 0 delegates the call to operating system-specific – and thus optimized – implementations. How to delete a file in JavaYou can delete a file (or a directory) with 1: 6 The directory on which you invoke 1 must be empty. Otherwise, the method will throw a 3. You can try this with the following code: 7 First, a temporary directory is created, then a temporary file in it. Then an attempt is made to delete the (non-empty) directory. How to create a symbolic link to a fileYou can create a symbolic link with the method 4. Attention: You have to specify target and source in reverse order as with all previous methods: first, the link path, then the path of the file to be linked. The following example creates a temporary file and then sets a symbolic link to the created file from the home directory. 8 This example works on Linux without restrictions. On Windows, you need administrative rights to create symbolic links. If these are missing, the following exception is thrown: 5 Summary and outlookThis fourth article in the series about files in Java introduced the most important directory and file operations. In the next part, I will show you how to write and read structured data with 6 and 7. We then move on to the following advanced topics:
As always, I appreciate it if you share the article or your feedback via the comment function. Would you like to be informed when the next part is published? Then to sign up for the HappyCoders newsletter. How to delete multiple files from a folder in Java?You can use the FileUtils. cleanDirectory() method to recursively delete all files and subdirectories within a directory, without deleting the directory itself. To delete a directory recursively and everything in it, you can use the FileUtils. deleteDirectory() method.
How to delete all the files in a directory in Java?Method 1: using delete() to delete files and empty folders. Provide the path of a directory.. Call user-defined method deleteDirectory() to delete all the files and subfolders.. How can we delete all files in a directory?Another option is to use the rm command to delete all files in a directory.. Open the terminal application.. To delete everything in a directory run: rm /path/to/dir/*. To remove all sub-directories and files: rm -r /path/to/dir/*. How to delete the contents of a folder in Java?How to delete a directory and its contents in Java. Use the Files. walk method to walk through all the files of the directory. ... . All the files are traversed in depth-first order. Reverse the stream and delete it from inner files.. Call Files. delete(path) to delete the file or directory.. |