Deleting Files in Java
To delete a file in Java, you can use the . This method deletes the files or directory from the given path.
Syntax
Following is the syntax of deleting a file using File.delete() method −
File file = new File("C:/java/hello.txt"); if(file.exists()){ file.delete(); }
Deleting File from Current Directory
Following is the example to demonstrate File.delete() method usage to delete an existing file in current directory−
Example
package com.tutorialspoint; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class FileTest { public static void main(String args[]) throws IOException { BufferedWriter out = new BufferedWriter (new FileWriter("test.txt")); out.write("test data"); out.close(); File file = new File("test.txt"); if(file.exists()) { boolean success = file.delete(); if (success) { System.out.println("The file has been successfully deleted."); }else { System.out.println("The file deletion failed."); } }else { System.out.println("The file is not present."); } } }
Output
The above code would create file test.txt and would write given numbers in binary format. Same would be the output on the stdout screen.
This will produce the following result −
The file has been successfully deleted.
Deleting File That Does Not Exist
Following is the example to demonstrate File.delete() method call to delete an non-existing file in current directory. As file is not present, it returns false as result.
Example
package com.tutorialspoint; import java.io.File; import java.io.IOException; public class FileTest { public static void main(String args[]) throws IOException { File file = new File("test1.txt"); boolean success = file.delete(); if (success) { System.out.println("The file has been successfully deleted."); }else { System.out.println("The file deletion failed."); } } }
Output
The above code would create file test.txt and would write given numbers in binary format. Same would be the output on the stdout screen.
This will produce the following result −
The file deletion failed.
Deleting All Files From Given Directory
Following is the example to demonstrate File.delete() method usage to delete all files in given directory recursively.
Example
package com.tutorialspoint; import java.io.File; import java.io.IOException; public class FileTest { public static void deleteFiles(File dirPath) { File filesList[] = dirPath.listFiles(); for(File file : filesList) { if(file.isFile()) { file.delete(); } else { deleteFiles(file); } } } public static void main(String args[]) throws IOException { //Creating a File object for directory File file = new File("D:\test"); //List of all files and directories deleteFiles(file); System.out.println("Files deleted."); } }
Output
The above code would create file test.txt and would write given numbers in binary format. Same would be the output on the stdout screen.
This will produce the following result −
Files deleted.