In this quick article, you'll learn how to delete a file in Java using both legacy API as well as new I/O API (NIO).
Using Files.delete()
Method
In Java 7+, you can use Files.delete()
— the static method from the NIO API to delete any file. If the file exists, it deletes it along with parent directories if they are empty. If it doesn't exist already, Files.delete()
throws a NoSuchFileException
exception.
Here is an example:
try {
// delete file
Files.delete(Paths.get("file.txt"));
} catch (IOException ex) {
ex.printStackTrace();
}
If you only want to delete an existing file, just use Files.deleteIfExists()
. It is similar to the above method except that it doesn't throw an exception if the file is not present:
Files.deleteIfExists(Paths.get("file.txt"));
Using File.delete()
Method
In Java 6 or below, you can use the File.delete()
method to remove a file from the file system. This method returns true
if the file is deleted successfully, otherwise false
if there is an error or the file is non-existent.
Here is an example:
// create file instance
File file = new File("file.txt");
// delete file
if(file.delete()) {
System.out.println("File is deleted!");
} else {
System.out.println("File doesn't exist.");
}
Further Reading
You may be interested in other Java I/O articles:
- Reading and Writing Files in Java
- How to Read and Write Text Files in Java
- How to Read and Write Binary Files in Java
- Reading and Writing Files using Java NIO API
- How to read a file line by line in Java
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.