Deleting a file or directory in Java is pretty simple. Create a File object and call the .delete() method on it.
import java.io.File; File file = new File(filePath); file.delete();
The .delete() method:
Returns true if the file/directory is deleted successfully
Returns false if the file/directory is not deleted (ie. file not found, file is open)
Throws a SecurityException if the application has insufficient permissions to delete the file/directory.
Full example with error checking:
import java.io.*; public class DeleteFile { public static void main(String[] args) { File file = new File("C://Temp//test.txt"); if (!file.exists()) { System.out.println("File not found"); return; } try { if (file.delete()) System.out.println("File successfully deleted"); else System.out.println("Failed to delete file"); } catch (SecurityException e) { System.out.println("Unable to delete file: " + e.getMessage() ); } } }
NOTES:
A directory must be empty before it can be deleted.
Some older versions of Java cannot delete files in Windows Vista when User Account Control is turned on. This can be fixed by updating Java or disabling UAC.
If a file cannot be deleted if it is open for reading/writing. Be sure to call the .close() method on the associated stream before trying to delete the file.
If you are still having trouble deleting a file check the .exists() method to make sure the system can find the file you are trying to delete. If it returns false double check that the path matches the file you are trying to delete.
Alternately you can use .deleteOnExit() instead of .delete() to delete files and directories when the program closes.
