Deleting a File
Problem
You need to delete one or more files from disk.
Solution
Use a java.io.File
object’s delete( )
method; it will delete files (subject
to permissions) and
directories
(subject to permissions and to the directory being empty).
Discussion
This is not very complicated. Simply construct a
File
object for the file you wish to delete, and
call its delete( )
method:
import java.io.*; /** * Delete a file from within Java */ public class Delete { public static void main(String[] argv) throws IOException { // Construct a File object for the backup created by editing // this source file. The file probably already exists. // My editor creates backups by putting ~ at the end of the name. File bkup = new File("Delete.java~"); // Quick, now, delete it immediately: bkup.delete( ); } }
Just recall the caveat about permissions in the Introduction to this
chapter: if you don’t have permission, you can get a return
value of false or, possibly, a SecurityException
.
Note also that there are some differences between platforms. Windows
95 allows Java to remove a file that has the read-only bit, but Unix
does not allow you to remove a file that you don’t have
permission on or to remove a directory that isn’t empty. Here
is a version of Delete
with error checking (and
reporting of success, too):
import java.io.*; /** * Delete a file from within Java, with error handling. */ public class Delete2 { public static void main(String argv[]) { for (int i=0; i<argv.length; i++) delete(argv[i]); ...
Get Java Cookbook 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.