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;
//  j  a v a  2  s.  c om
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   java2  s  .c om
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
Home » Java Tutorial » File
File
File across Operating System
File properties
File creation
File path
File path compare
File delete
File parent folder
File drive root
File size/length
File new directories
File rename
File modified time
File executable, readable or writable
File location to URI
File copy