Introduction
In this blog, we’ll learn how to delete a file or directory in Java. It provides methods for deleting files from programs. Unlike typical delete operations in any operating system, files removed with the java program are permanently erased and does not go to the trash or the recycling bin.
The article demonstrates two ways of deleting a File in java:
- Delete file using java.nio.file.files.deleteifexists(Path p)
- Delete file using java.io.File.delete() function
Delete a file using java.nio.file.files.deleteifexists(Path p)
The java.nio.file.files.deleteifexists(Path p) method also deletes the file or directory defined by abstract pathname. Generally, we use this method when we have to delete a temporary file. It is not possible to cancel a request once it has been made. As a result, this method should be used with extra caution.
CODE:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) {
try {
// this line creates a file object
Path filePath = Paths.get("JavaFile.java");
// deletes the file and returns true if the file is deleted, otherwise false
boolean isFileDeleted = Files.deleteIfExists(filePath);
if (isFileDeleted) {
System.out.println("JavaFile.java is successfully deleted.");
} else {
System.out.println("File doesn't exist. Can’t delete the file which does not exist!");
}
} catch (Exception e) {
e.getStackTrace();
}
}
}
Output:
The delete() function of the File class was used to delete the file named JavaFile.java in the example given above.
If the file is present, the message JavaFile.java has been successfully deleted will be shown. Otherwise, the message File doesn't exist. Can’t delete the file which does not exist! is shown.
Try it by yourself on Java Online Compiler.