Recipe 11.4 Deleting a File


Problem

You need to delete one or more files from the disk.

Solution

Use a java.io.File object's delete( ) method; it deletes 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 target = new File("Delete.java~");         // Now delete the file from disk.         target.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. Some versions of Windows allow 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]);     }     public static void delete(String fileName) {         try {             // Construct a File object for the file to be deleted.             File target = new File(fileName);             // Now delete the file from disk.             if (target.delete( ))                 System.out.println("** Deleted " + fileName);             else                 System.err.println("Failed to delete " + fileName);         } catch (SecurityException e) {                 System.err.println("Unable to delete " + fileName +                 "(" + e.getMessage( ) + ")");         }     } }

Running it, we get this:

$ ls -ld ? -rw-r--r--  1 ian  ian    0 Oct  8 16:50 a drwxr-xr-x  2 ian  ian  512 Oct  8 16:50 b drwxr-xr-x  3 ian  ian  512 Oct  8 16:50 c $ java Delete2 ? **Deleted** a **Deleted** b Failed to delete c $ ls -l  c total 2 drwxr-xr-x  2 ian  ian  512 Oct  8 16:50 d $ java Delete2 c/d c **Deleted** c/d **Deleted** c $



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon

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