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.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.");
}
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024