Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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]); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata