How to Delete a File In Java Programming
In this tutorial you are gong to learn how to delete a file using Java program, that is we are going to write a Java program that will delete a file from the disk.
To Delete a File in Java we use the File.delete() method of the Java I/O package. This method will delete the file from the physical location on the disk and will return the boolean value ‘true‘ if the operation is successful and will return ‘false‘ if the file is not deleted or the operation fails.
No parameters supplied.
boolean: ‘true’ or ‘false’
- true: When the file is successfully deleted
- false: When the file is not present, or the operation is not successful.
So below is the example code in Java to delete a file.
public class DeleteAFileInJava
public static void main(String args)
// Initialize the location of the file
String fileLoc = "c:\\mytestfile.txt";
// Create a new File Object
File myFile = new File(fileLoc);
// Physically the file is deleted and simultaneously we are checking the
// returned result from the method delete()
System.out.println("My New File Deleted");
System.out.println("File does Not exist.");
The above program will output My New File Deleted if the deletion is successful else it will output File does Not Exist.