How do I delete a file in Java?

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.example.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.");
        }
    }
}

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply