Share on Google+Share on Google+

Java - Deleting the file or Directory

In this section, you will learn how to delete the file or directory.

Java - Deleting File



In this section, you will learn how a specified file or directory is deleted after checking the existence of the. This topic is related to the I/O (input/output) of package.

In this example we are using File class of package. The File class is an abstract representation of file and directory pathnames. 


This program takes an input for the file name to be deleted and deletes the specified file if that exists. We will be declaring a function called deletefile() which deletes the specified directory or file.

deletefile(String file)

The function deletefile(String file) takes file name as parameter. The function creates a new File instance for the file name passed as parameter

File f1 = new File(file);

and delete the file using delete function f1.delete(); which return the Boolean value (true/false). It returns true if and only if the file or directory is successfully deleted; false otherwise.

Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted.


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

Code of the Program :

public class DeleteFile{
private static void deletefile(String file){
File f1 = new File(file);
boolean success = f1.delete();

    if (!success){
System.out.println("Deletion failed.");
System.out.println("File deleted.");
public static void main(String[] args){
case 0: System.out.println("File has not mentioned.");
case 1: deletefile(args[0]);
default : System.out.println("Multiple files are not allow.");

Download File Deletion Example


Posted on: April 16, 2007 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Java - Deleting the file or Directory   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
May 24, 2011
delete fail

According to this method,delete failed?