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 delete using this method is not empty, the delete() method will return a boolean false value. If the file or directory that you are trying to delete does not exist, the delete() method will still return a false value, without throwing an exception.

Another useful method available related to deleting files and directories is the deleteOnExit() method of the File class. Calling the deleteOnExit() method requests that the file or directory represented by this File object be deleted automatically when the Java virtual machine terminates.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net