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 create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023