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 build simple search page using ZK and Spring Boot? - March 8, 2023
- How do I calculate days between two dates excluding weekends and holidays? - January 12, 2023
- How do I discover the quarter of a given date? - January 11, 2023