File delete

In this chapter you will learn:

  1. How to delete a file in Java
  2. How to delete a file on exiting the JVM

Delete a file

When deleting a file we can choose to delete right away or delete when existing JVM.

  • boolean delete() deletes the file or directory.
  • void deleteOnExit() requests that the file or directory to be deleted when the virtual machine terminates.
import java.io.File;
import java.io.IOException;
/*from  jav a  2s .co m*/
public class Main {

  public static void main(String[] args) {

    
    try {
      File tempFile = File.createTempFile("abc","txt",new File("c:\\"));
      tempFile.delete();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Delete a file on exit

The following code uses deleteOnExit method:

import java.io.File;
import java.io.IOException;
/*from ja v  a  2 s  .c o  m*/
public class Main {

  public static void main(String[] args) {

    
    try {
      File tempFile = File.createTempFile("abc","txt",new File("c:\\"));
      tempFile.deleteOnExit();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Next chapter...

What you will learn in the next chapter:

  1. How to get the parent folder
  2. How to list all files and folders within a directory
  3. How to use FileFilter to examine each file in details