File management (good old CRUD: create, read, update, delete) is quite common operation in software development. In this short post I would like to present 2 ways of removing files in Java.
Method available in every Java version
Every Java version provides delete() method in File class which can be used to delete file:
File filePath = new File("SomeFileToDelete.txt"); boolean success = filePath.delete();
The delete() method returns boolean value which informs whether the file was removed successfully. If the file did not exist before call, the method return false.
This method can also delete empty directory. If the directory does not exist before the call or is not empty, the method returns false.
It is important to note that this method does not throw any exception in case of failure (except SecurityException). Additionally, it does not have any way to inform why the delete operation failed.
New method since Java 7
Because of the above limitations the new static method delete() in Files class was introduced in Java 7:
Path filePath = Paths.get("SomeFileToDelete.txt"); Files.delete(filePath);
The static method Files.delete() deletes a file, empty directory or a link (not the file pointed to). The real improvement over the previous method is that it properly utilizes exceptions and reports more information about the root cause if the file/directory/link cannot be removed for some reason. The following exceptions can be reported:
- NoSuchFileException if the file/directory/link does not exist
- DirectoryNotEmptyException if the file is a directory and is not empty
- IOException if an IO error occurs (e.g. missing file permissions)
- SecurityException if the operation is not allowed by SecurityManager
There is an additional method Files.deleteIfExists which also deletes the file but does not throw exception NoSuchFileException if the file does not exist. This method can still throw other above exceptions to indicate error.
Common problems
Sometimes the delete operation may fail with the following error message:
The process cannot access the file because it is being used by another process
This error is quite popular on Windows and means that some process or application is still using the file (e.g. read or write to the file). Therefore, Windows operating system blocks the file removal. In order to remove the file successfully, it needs to be closed first.