Deleting a File or Directory

File f = new File("somefile.txt");
											boolean result = f.delete();

Deleting a file using the File class is a simple task. We first create a File object specifying the name of the file that we want to delete. We then call the File object’s delete() method. A boolean value of true is returned if the file was deleted successfully; otherwise, a false is returned.

The delete() method can also be used to delete a directory. To delete a directory, you would create the File object, specifying a directory name instead of a filename. Here, we show how you would delete a directory:

File directory = new File("files/images");
directory.delete();

The directory will only be deleted if it is empty. If the directory you are trying to ...

Get Java™ Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.