In this example you will see how to delete a file in Java. To delete a file we start by creating a File
object that represent the file to be deleted. We use the exists()
method to check if the file is exists before we try to delete it.
To delete the file we call the delete()
method of the File
object. If the file was successfully deleted the method will return a boolean true
result, otherwise it will return false
. Let’s try the code snippet below.
package org.kodejava.example.io;
import java.io.File;
public class FileDeleteExample {
public static void main(String[] args) {
// When want to delete a file named readme.txt
File file = new File("write.txt");
// Checks if the file is exists before deletion.
if (file.exists()) {
System.out.println("Deleting " + file.getAbsolutePath());
// Use the delete method to delete the given file.
boolean deleted = file.delete();
if (deleted) {
System.out.println(file.getAbsolutePath() + " was deleted.");
}
} else {
System.out.println(file.getAbsolutePath() + " not found.");
}
}
}
Wayan Saryada
Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳
Latest posts by Wayan Saryada (see all)
- How do I set the time of java.util.Date instance to 00:00:00? - October 24, 2019
- How to Install Consolas Font in Mac OS X? - March 29, 2019
- How do I clear the current command line in terminal? - February 14, 2019