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]);
    }

    public static void delete(String fileName) {
        try {
            // Construct a File object for the file to be deleted.
            File bkup = new File(fileName);
            // Quick, now, delete it immediately:
            if (!bkup.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
$
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.97.187