Java program to Delete a file :
In this example, we will learn how to delete a file in Java. In the below program, the full path of the file is stored in ‘fileName’ variable. First we create one ‘File’ object using ‘File(fileName)’ constructor. Then we will delete that file using ‘delete()’ function. It will return ‘true’ if the file is deleted successfully. ‘false’ otherwise.
Let’s take a look into the program :
Example Program :
import java.io.File;
public class Main {
/**
* Utility functions for System.out.println() and System.out.print()
*/
private static void println(String str) {
System.out.println(str);
}
private static final String fileName = "new.txt"; //file name with path
public static void main(String args[]) {
File file = new File(fileName);
if(file.delete()){
println("File is deleted successfully.");
}else{
println("Not able to delete the file");
}
}
}
To run this program , change ‘new.txt’ with the full path of your file you want to delete.