How to delete a file in Java

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:

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.