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); } }
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()); } } }
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.docxif 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"));