Java I/O How to - Delete file or directory when the program ends








Question

We would like to know how to delete file or directory when the program ends.

Answer


import java.io.File;
public class MainClass {
  public static void main(String[] a) {
    File file = new File("c:\\test\\test.txt");
    file.deleteOnExit();
  }
}

The code above generates the following result.