- How to delete a directory recursively in Java
- You might also like.
- Delete Files in a Directory Using Java
- Delete Files in a Directory Using delete() of File Class in Java
- Delete Files in a Directory Using Java 8 Streams and NIO2
- Delete Files in a Directory Using Apache Common IO
- Conclusion
- Related Article — Java File
- Java remove all files in folder
- How to move a file in Java
- How to move a directory including all subdirectories
- How to rename file with Java
- How to copy a file in Java
- How to delete a file in Java
- How to create a symbolic link to a file
- Summary and outlook
How to delete a directory recursively in Java
In an earlier article, we looked at different ways of deleting a directory in Java. In this article, you’ll learn how to delete a non-empty directory recursively — delete all its files and sub-folders.
Java provides multiple methods to delete a directory. However, the directory must be emptied before we delete it. To remove all contents of a particular directory programmatically, we need to use recursion as explained below:
- List all contents (files & sub-folders) of the directory to be deleted.
- Delete all regular files of the current directory (exist from recursion).
- For each sub-folder of the current directory, go back to step 1 (recursive step).
- Delete the directory.
Let us look at different ways to implement the above simple recursive algorithm.
In Java 8 or higher, you can use Files.walk() from NIO API (classes in java.nio.* package) to recursively delete a non-empty directory. This method returns a Stream that can be used to delete all files and sub-folders as shown below:
try // create a stream StreamPath> files = Files.walk(Paths.get("dir")); // delete directory including files and sub-folders files.sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::deleteOnExit); // close the stream files.close(); > catch (IOException ex) ex.printStackTrace(); >
In the above example, Files.walk() returns a Stream of Path . We sorted it in the reverse order to place the paths indicating the contents of directories before directories itself. Afterward, it maps Path to File and deletes each File .
To delete a non-empty directory using Java legacy I/O API, we need to manually write a recursive function to implement the above algorithm. Here is how it looks like:
public void deleteDir(File dir) File[] files = dir.listFiles(); if(files != null) for (final File file : files) deleteDir(file); > > dir.delete(); >
As you can see above, we are using File.listFiles() method to list all files and sub-directories in the directory. For each file, we recursively call deleteDir() method. In the end, we delete the directory using File.delete() . Now you can call the above method as follows:
File dir = new File("dir"); deleteDir(dir);
The Apache Commons IO library provides FileUtils.deleteDirectory() method to delete a directory recursively including all files and sub-directories:
try // directory path File dir = new File("dir"); // delete directory recursively FileUtils.deleteDirectory(dir); > catch (IOException ex) ex.printStackTrace(); >
dependency> groupId>commons-iogroupId> artifactId>commons-ioartifactId> version>2.6version> dependency>
implementation 'commons-io:commons-io:2.6'
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.
You might also like.
Delete Files in a Directory Using Java
- Delete Files in a Directory Using delete() of File Class in Java
- Delete Files in a Directory Using Java 8 Streams and NIO2
- Delete Files in a Directory Using Apache Common IO
- Conclusion
In this article, we will learn how to delete files present inside the folder without deleting the folder itself.
There are multiple ways to do this. Let’s look at them one by one.
Delete Files in a Directory Using delete() of File Class in Java
In Java, we have the java.io.File class, which contains a method called delete() used to delete files and empty directories.
Let’s assume in our system’s D: drive a directory with a name as test exists, and let’s say it contains some text files and some sub-folders. Now, let’s see how to delete this using the delete() method.
import java.io.File; public class Example public static void main(String[] args) String path = "D:\\test"; File obj = new File(path); for (File temp: Objects.requireNonNull(obj.listFiles())) if (!temp.isDirectory()) temp.delete(); > > > >
When the above code is executed, we can see that all the files inside the test are deleted, but the main folder test and the sub-folders are untouched.
In the above, we have created a string variable that stores the path of the directory. Then we used this path to create our file object obj .
Then we used the listFiles() method to list the contents present at that path.
Using the if condition, we check if it’s a directory or a file. If it is a file, we delete it; else, we do nothing.
Delete Files in a Directory Using Java 8 Streams and NIO2
In this method, we can use the Files.walk(Path) method that returns Stream , which contains all the files and sub-folders present in that path .
Then we check if it’s a directory or a file using the if condition. If it is a file, we delete it; else, we do nothing.
import java.io.*; import java.nio.file.*; import java.util.*; public class Demo public static void main(String[] args)throws IOException Path path = Paths.get("D:\\test"); Files.walk(path).sorted(Comparator.reverseOrder()) .forEach(data-> try if(!Files.isDirectory(data)) System.out.println("deleting: " + data); Files.delete(data); > >catch(IOException obj) obj.printStackTrace(); > >); > >
deleting: D:\test\subfolder 2\file4.txt deleting: D:\test\subfolder 1\file3.txt deleting: D:\test\file2.txt deleting: D:\test\file1.txt
When the above code is executed, it deletes all the files of the directory and sub-directory files in a Depth First Search fashion.
We can observe that the directory test and the sub-directories subfolder 1 and subfolder 2 remained intact.
Delete Files in a Directory Using Apache Common IO
So far, all the methods we have seen are plain old Java methods that use some concepts of recursion along with file and stream methods. But we can use Apache Common IO FileUtils.cleanDirectory() to recursively delete all the files and the sub-directories within the main directory without deleting the main directory itself.
The main advantage of using this over primitive Java methods is that the line of codes (LOC) is significantly less, making it an easy and more efficient way of writing.
To use Apache common IO, we must first add the dependencies in our pom.xml file.
commons-io commons-io 2.11.0
import java.io.*; import org.apache.commons.io.FileUtils; public class Example public static void main(String[] args)throws IOException String path = "D:\\test"; File obj = new File(path); FileUtils.cleanDirectory(obj); > >
Conclusion
This article has shown different ways of deleting directories using Java. We understood how to use the delete() method and Java 8 streams and how using Apache commons IO could be more efficient and time-saving where LOC (line of codes) greatly affects the performance of our project.
A technophile and a Big Data developer by passion. Loves developing advance C++ and Java applications in free time works as SME at Chegg where I help students with there doubts and assignments in the field of Computer Science.
Related Article — Java File
Java remove all files in folder
After the last chapter concluded with accessing the temporary directory, this one starts with a shortcut to creating temporary files:
Path tempFile = Files.createTempFile("happycoders-", ".tmp");
Code language: Java (java)
The two parameters are a prefix and a suffix. The createTempFile() method will insert a random number between them. When I run the method repeatedly on my Windows system and print the variable tempFile to the console, I get the following output:
tempFile = C:\Users\svenw\AppData\Local\Temp\happycoders-7164892815754554616.tmp tempFile = C:\Users\svenw\AppData\Local\Temp\happycoders-3557939636108137420.tmp tempFile = C:\Users\svenw\AppData\Local\Temp\happycoders-16515581992479122220.tmp tempFile = C:\Users\svenw\AppData\Local\Temp\happycoders-4078166990204004103.tmp
Code language: plaintext (plaintext)
tempFile = /tmp/happycoders-6859515894563322081.tmp tempFile = /tmp/happycoders-3688163816397144832.tmp tempFile = /tmp/happycoders-2576679508175526427.tmp tempFile = /tmp/happycoders-8074586277964353976.tmp
Code language: plaintext (plaintext)
It is essential to know that createTempFile() does not only create the respective Path object but actually creates an empty file.
How to move a file in Java
To move a file, use the method Files.move() . The following example creates a temporary file and moves it to the home directory of the logged-on user:
Path tempFile = Files.createTempFile("happycoders-", ".tmp"); Path targetDir = Path.of(System.getProperty("user.home")); Path target = targetDir.resolve(tempFile.getFileName()); Files.move(tempFile, target);
Code language: Java (java)
The second parameter of the move() method must represent the target file, not the target directory! If you invoked Files.move(tempFile, targetDir) here, you would get a FileAlreadyExistsException . Therefore, in the example, we use the resolve() method to concatenate the targetDir with the name of the file to be copied.
How to move a directory including all subdirectories
You 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:
Path tempDir1 = Files.createTempDirectory("happycoders-"); Path tempDir2 = Files.createTempDirectory("happycoders-"); Path tempFile = Files.createTempFile(tempDir1, "happycoders-", ".tmp"); Path target = tempDir2.resolve(tempDir1.getFileName()); Files.move(tempDir1, target);
Code language: Java (java)
How to rename file with Java
After 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»:
Path tempFile = Files.createTempFile("happycoders-", ".tmp"); Path target = tempFile.resolveSibling("happycoders.tmp"); Files.move(tempFile, target);
Code language: Java (java)
Invoking tempFile.resolveSibling(«happycoders.tmp») is a shortcut for tempFile.getParent().resolve(«happycoders.tmp») : The directory is extracted from the source file and concatenated with the new file name.
How to copy a file in Java
Copying a file is similar to renaming it. The following example copies a temporary file to the home directory:
Path tempFile = Files.createTempFile("happycoders-", ".tmp"); Path targetDir = Path.of(System.getProperty("user.home")); Path target = targetDir.resolve(tempFile.getFileName()); Files.copy(tempFile, target);
Code language: Java (java)
This method has a significant advantage over proprietary implementations with FileInputStream and FileOutputStream , as they were necessary before Java 7 and the NIO.2 File API: Files.copy() delegates the call to operating system-specific – and thus optimized – implementations.
How to delete a file in Java
Path tempFile = Files.createTempFile("happycoders-", ".tmp"); Files.delete(tempFile);
Code language: Java (java)
The directory on which you invoke Files.delete() must be empty. Otherwise, the method will throw a DirectoryNotEmptyException . You can try this with the following code:
Path tempDir = Files.createTempDirectory("happycoders-"); Path tempFile = Files.createTempFile(tempDir, "happycoders-", ".tmp"); Files.delete(tempDir);
Code language: Java (java)
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 file
You can create a symbolic link with the method Files.createSymbolicLink() . 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.
Path tempFile = Files.createTempFile("happycoders-", ".tmp"); Path linkDir = Paths.get(System.getProperty("user.home")); Path link = linkDir.resolve(tempFile.getFileName()); Files.createSymbolicLink(link, tempFile);
Code language: Java (java)
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: FileSystemException: [link]: A required privilege is not held by the client.
Summary and outlook
- NIO channels and buffers introduced in Java 1.4, to speed up working with large files
- Memory-mapped I/O for convenient and blazing-fast file access without streams
- File locking, to access the same files in parallel – i.e., from several threads or processes – without conflict
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 click here to sign up for the HappyCoders newsletter.