In this article we will show you the solution of java delete files in directory, File.delete() is a method of the File class that can be used to delete a file in Java. This method destroys any files or directories associated with the abstract pathname specified in the pathname argument.
When the pathname specifies a directory, that directory must be empty to be deleted. Delete() is a method in the Files class that can be used to delete a file in Java.
An object that is an instance of the File class can also be deleted using the delete() method. We will now discuss the idea of how to delete files in a directory in java with an example.
Step By Step Guide On Java Delete Files In Directory :-
import java.io.File; class TC{ public static void deleteDirectory(File file) { // store all the paths of files and folders present // inside directory for (File subfile : file.listFiles()) { if (subfile.isDirectory()) { deleteDirectory(subfile); } // delete files and empty subfolders subfile.delete(); } } public static void main(String[] args) { // store file path String filepath = "C:\\TC"; File file = new File(filepath); // call deleteDirectory function to delete // subdirectory and files deleteDirectory(file); file.delete(); } }
- Working with files and directories is handled by the File class.
- Our class TC is defined in the following way.
- An object called File is passed as a parameter to a static method called deleteDirectory. An entire directory and any subdirectories and files under it will be deleted with the help of this method.
- An iterative loop is used within the method to traverse all the files and folders within the directory represented by the File object.
- If the current file or folder is a directory, we call the deleteDirectory function recursively to delete all the files and folders inside it.
- In this example, we use the delete() method to delete the current file or folder.
- For testing the deleteDirectory() function, we define a main() method.
- As soon as we specify the path to the file, we create a new File object.
- Delete all the contents of the directory by calling deleteDirectory() with the file object as a parameter.
- The final step is to use the delete() method in order to delete the directory itself.
Conclusion :-
As a result, we have successfully learned how to delete files in a directory in java with an example.
The purpose of this quick tutorial was to explore different methods of deleting a directory.
Recursion was demonstrated in the process of deleting files, but we also looked at some libraries of deleted files.
I hope this article on java delete files in directory helps you and the steps and method mentioned above are easy to follow and implement.