Java Development
Articles
Delete file using File.delete( ) method
Published: September 3, 2007
Print    Email

This source code shows you how to delete a file by using the File.delete( ) method in Java.

Method:

Class File

public boolean delete()

Deletes the file or directory denoted by this abstract pathname.

Returns:
true if and only if the file or directory is successfully deleted; false otherwise

Example:

import java.io.*;

public class DeleteFiles {
    public static void main(String[  ] args) {
        if (args.length != 1) {
            System.err.println("Usage: java Delete ");
            System.exit(0);
        }
        try { delete(args[0]); }
        catch (IllegalArgumentException e) {
            System.err.println(e.getMessage( ));
        }
    }    
    public static void delete(String filename) {
        File f = new File(filename);
        if (!f.exists( )) fail("Delete: no such file or directory: " +filename);
        if (!f.canWrite( )) fail("Delete: write protected: " + filename);
        if (f.isDirectory( )) {
            String[  ] files = f.list( );
            if (files.length > 0)
                fail("Delete: directory not empty: " + filename);
        }
        boolean success = f.delete( );
        if (!success) fail("Delete: deletion failed");
    }
}

 



View Comments (0)
Latest Articles
Java Threads

Delete file using File.delete( ) method

Copying Files in Java

Downloading the Contents of a URL

Java FTP Source Code

Processing XML with Java

Generating Random Numbers

Java Lexical Structure

Serializing

Learning java
Latest Posts
Last news from Bahrain islands
Posted by ribrothetit

Please, help me
Posted by FthrOfIIIChlds

Beginners tutorial!
Posted by perz

Health and Beauty FOREVER
Posted by SKACTANDATE

buy xanax fergana
Posted by FleseeKip

Users Online
Online Now: 4
0 Members | 4 Guests

Most users ever online was 74 on November 6, 2007 at 13:07 PM.
Newsletter
Subscribe to our Newsletter!

Your Email: