To delete a file or directory, use the delete() method of the File class.
A directory must be empty before deleting.
The method returns true if the file/directory is deleted; otherwise, it returns false.
You can delay the deletion of a file until the JVM terminates by using the deleteOnExit() method.
It is useful if you create temporary files that you want to delete when your program exits.
import java.io.File; public class Main { public static void main(String[] args) { // To delete the dummy.txt file immediately File myFile = new File("dummy.txt"); myFile.delete();/* w w w.j a va2 s .co m*/ // To delete the dummy.txt file when the JVM terminates myFile = new File("dummy.txt"); myFile.deleteOnExit(); } }