Java Delete Files
In this page:
Deleting a File with the File Class
A file can be removed from disk using the File class's delete method, which attempts to delete the file at that path and returns a boolean indicating whether the deletion actually succeeded.
Example: Deleting a File with the File Class
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
File file = new File("temp.txt");
file.createNewFile();
boolean deleted = file.delete();
System.out.println(deleted);
}
}
Login to try C/C++/Java/PHP code in the editor
Checking Deletion Success
The delete method never throws an exception on failure -- it silently returns false whether the file didn't exist in the first place or the deletion failed for some other reason like a permissions issue.
Example: Checking Deletion Success
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("does-not-exist.txt");
boolean deleted = file.delete(); // false, no exception thrown
System.out.println(deleted);
}
}
Login to try C/C++/Java/PHP code in the editor
Deleting Directories
The same delete method also removes empty directories, but it will fail and return false if the directory still contains any files or subdirectories, since it does not delete recursively.
Example: Deleting Directories
import java.io.File;
public class Main {
public static void main(String[] args) {
File dir = new File("empty-folder");
dir.mkdir();
System.out.println(dir.delete()); // succeeds: directory is empty
}
}
Login to try C/C++/Java/PHP code in the editor
Deleting Files with NIO
The NIO Files utility class offers delete, which throws a specific exception on failure, and deleteIfExists, which safely returns false instead of throwing when the target file simply isn't there.
Example: Deleting Files with NIO
import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
Path path = Path.of("temp.txt");
Files.createFile(path);
Files.delete(path); // throws on failure
System.out.println(Files.deleteIfExists(path)); // false: already gone
}
}
Login to try C/C++/Java/PHP code in the editor
Handling Deletion Errors
Handling delete failures well means checking the boolean or exception the API provides rather than assuming success, since a failed deletion often points to the file being open elsewhere or a lack of file system permissions.
Example: Handling Deletion Errors
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("temp.txt");
if (!file.delete()) {
System.out.println("Deletion failed: check permissions or existence");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: