# How to delete a file in Java

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Dec 8, 2019. Topics: Java.
Canonical URL: https://attacomsian.com/blog/java-delete-file

> A short article to learn 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()` &mdash; 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:

```java
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: 

```java
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:

```java
// 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](https://attacomsian.com/blog/java-read-write-files)
* [How to Read and Write Text Files in Java](https://attacomsian.com/blog/java-read-write-text-files)
* [How to Read and Write Binary Files in Java](https://attacomsian.com/blog/java-read-write-binary-files)
* [Reading and Writing Files using Java NIO API](https://attacomsian.com/blog/java-read-write-files-nio-api)
* [How to read a file line by line in Java](https://attacomsian.com/blog/how-to-read-a-file-line-by-line-in-java)
