Even though creating a file in Java is easy, deleting a file is easier. In this tutorial, I will guide you how to delete a file in Java.
The File object, which is the main file management object since Java version 6 and earlier, cannot be ignored.
In this object, we can use the delete() method to delete any file. The condition to delete a file is that: the file must exist on your computer.
Using this method will return a boolean value, true if we delete successfully, otherwise, if the value is false then surely the error occurs.
1 2 3 4 5 6 7 8 9 |
public class FileDeletion { public static void main(String[] args) { File file = new File("E:\\note.txt"); if (file.exists() && file.delete()) { System.out.println("File deleted successfully"); } } } |
If you do not use the File object, you can also use the Files object introduced since Java 7. This object provides us with a method called delete() to delete any file.
1 2 3 4 5 6 7 8 9 10 11 12 |
public class FileDeletion { public static void main(String[] args) { try { Path path = Paths.get("E:\\test.txt"); Files.delete(path); } catch (IOException e) { e.printStackTrace(); } } } |