Java - File Delete by File Object


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.



public class Main {
  public static void main(String[] args) {
    // To delete the dummy.txt file immediately
    File myFile = new File("dummy.txt");
    myFile.delete();/*from w ww  . java2  s .  c  o m*/

    // To delete the dummy.txt file when the JVM terminates
    myFile = new File("dummy.txt");


Related Topic