Skip to main content

Section 8.5 Deleting Files

Lastly, we will take a look at using Java to delete a file. This is pretty straight-forward and follows the structure used to create files. Listingย 8.5.1 shows the CreateFile class from before that will be used to create a file that we will soon delete:
Listing 8.5.1.
And finally, Listingย 8.5.2 shows the Java code that deletes a file. We will call this class DeleteFile:
Listing 8.5.2.
Note that this is almost identical to the code within the try block of the CreateFile class that we made earlier. The key difference is the use of the delete() method which will delete the file with the name that was linked to the myFile object. Similar to the createNewFile() method, it will return true if the file exists and can be deleted, and false if the file cannot be deleted.
You have attempted of activities on this page.