Share this page 

Delete a file Tag(s): IO


The traditional way is
import java.io.File;

public class Test {
   public static void main(String[] args) {
      File f = new File("c:/temp/foo.txt");
      boolean res = f.delete();
      System.out.println("Deleted ? " + res);
   }
}
If the file is found and deleted then the result is true. If false, you don't have much information about the reason why the delete has failed.

A better way is :

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Test {
   public static void main(String[] args) {
      try {
         Files.delete(Paths.get("c:/temp/foo.docx"));
      } catch (IOException e) {
         System.out.println(e.getMessage());
      }
   }
}
then if the file is openened and can't be deleted, an exception is thrown :
java.nio.file.FileSystemException: c:\temp\foo.docx: The process cannot access the file because it is being used by another process.
or if the file is missing :
java.nio.file.NoSuchFileException: c:\temp\foo.docx
if you want to delete a file but don't care if it's missing then simply use :
Files.deleteIfExists(Paths.get("c:/temp/foo.docx"));