Delete a File in Java
Java provides multiple ways to delete a file. The older java.io.File API provides the delete() method, while the newer java.nio.file.Files API provides Files.delete() and Files.deleteIfExists().
File.delete() returns a boolean value indicating whether the deletion succeeded. Files.delete() reports failures with exceptions, which usually makes it easier to determine why a file could not be deleted.
Delete a File using File.delete()
To delete a file using File.delete(), create a File object for the file path and call its delete() method.
- Create a
Fileobject that represents the file you want to delete. - Call
delete()on theFileobject. - Check the returned boolean value. A return value of
truemeans the file was deleted, whilefalsemeans the deletion did not succeed.
Example: delete data.txt with File.delete()
In this example, we delete a file named data.txt from the files directory.
Make sure that the file you are deleting is present.
DeleteFile.java
import java.io.File;
/**
* Java Example Program to Delete File
*/
public class DeleteFile {
public static void main(String[] args) {
File originalFile = new File("files/data.txt");
//delete file
boolean isDeleteDone = originalFile.delete();
//print if the delete operation is successful
System.out.println("Delete Done: "+isDeleteDone);
}
}
Run the above Java program.
Output
Delete Done: true
Here, delete() returned true, which means the file was successfully deleted.
File.delete() when the file does not exist
If the specified file does not exist, File.delete() cannot delete it and returns false.
DeleteFile.java
import java.io.File;
/**
* Java Example Program to Delete File
*/
public class DeleteFile {
public static void main(String[] args) {
File originalFile = new File("files/data1.txt");
//delete file
boolean isDeleteDone = originalFile.delete();
//print if the delete operation is successful
System.out.println("Delete Done: "+isDeleteDone);
}
}
In this example, there is no file at files/data1.txt, so the method returns false.
Output
Delete Done: false
Delete a File using Files.delete()
The java.nio.file.Files.delete() method deletes the file represented by a Path. Unlike File.delete(), it does not return a boolean value. If the deletion cannot be completed, it throws an exception describing the failure.
Files.delete(path);
Example: delete data.txt with Files.delete()
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class DeleteFileUsingNio {
public static void main(String[] args) {
Path path = Path.of("files/data.txt");
try {
Files.delete(path);
System.out.println("File deleted successfully.");
} catch (IOException e) {
System.out.println("Could not delete file: " + e.getMessage());
}
}
}
If the file exists and Java has permission to delete it, Files.delete() removes the file. If the file does not exist, a NoSuchFileException is normally thrown. Other I/O problems are also reported through exceptions.
Delete a File Only If It Exists with Files.deleteIfExists()
When a missing file should not be treated as an error, use Files.deleteIfExists(). It returns true when a file was deleted and false when no file existed at the specified path.
boolean deleted = Files.deleteIfExists(path);
Example: delete a Java file if it exists
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class DeleteFileIfExists {
public static void main(String[] args) {
Path path = Path.of("files/data.txt");
try {
boolean deleted = Files.deleteIfExists(path);
System.out.println("File deleted: " + deleted);
} catch (IOException e) {
System.out.println("Could not delete file: " + e.getMessage());
}
}
}
If files/data.txt exists and is deleted, the method returns true. If it is already absent, the method returns false instead of throwing NoSuchFileException.
Delete a File from a Path in Java
With the NIO API, a file location is represented by a Path. The path may be relative to the program’s working directory or absolute.
Path relativePath = Path.of("files/data.txt");
Files.deleteIfExists(relativePath);
If a relative path appears correct but the file is not found, check the application’s current working directory. A relative path such as files/data.txt is resolved from that location, not necessarily from the directory containing the Java source file.
Why File.delete() Can Return false
A false result from File.delete() tells you that the deletion failed, but it does not explain the exact reason. Common causes include:
- The file does not exist: verify that the path and file name are correct.
- The path points to a non-empty directory: deleting a directory with these APIs generally requires the directory to be empty first.
- Insufficient permissions: the Java process may not have permission to remove the file or modify its parent directory.
- The path is different from the one expected: relative paths depend on the application’s working directory.
- The file system prevents the operation: deletion behavior can also depend on the operating system and file system.
If you need to diagnose deletion failures, Files.delete() is often more useful because exceptions distinguish problems such as a missing file, a non-empty directory, or denied access.
Delete an Empty Directory in Java
The same deletion APIs can remove a directory when it is empty. For example, Files.delete() can delete an empty directory represented by a Path.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class DeleteEmptyDirectory {
public static void main(String[] args) throws IOException {
Path directory = Path.of("files/old-data");
Files.delete(directory);
}
}
If the directory contains files or subdirectories, Files.delete() does not recursively remove those contents. A recursive directory deletion requires traversing and deleting the contained entries before deleting the directory itself.
File.delete() vs Files.delete() vs Files.deleteIfExists()
| Method | Result when deletion succeeds | Result when file is missing | Error handling |
|---|---|---|---|
File.delete() | Returns true | Returns false | Usually reports failure only through the boolean result |
Files.delete() | Returns normally | Throws NoSuchFileException | Throws an IOException subtype describing the failure |
Files.deleteIfExists() | Returns true | Returns false | Still throws an exception for other I/O failures |
Use File.delete() when working with existing File-based code and make sure to check its return value. For newer code, Files.delete() is useful when a missing file should be treated as an error, while Files.deleteIfExists() is convenient when it is acceptable for the file to already be absent.
Java File Deletion Summary
Java files can be deleted with File.delete(), Files.delete(), or Files.deleteIfExists(). File.delete() reports success or failure through a boolean value. The NIO methods use Path objects and provide more detailed error handling through exceptions. When deleting a file only when it is present, Files.deleteIfExists() avoids treating a missing file as an error.
In this Java Tutorial, we learned how to delete File in Java and how to be sure if the delete operation is successful.
TutorialKart.com