How to delete file in java ?

In this section we will learn how to write a program to delete a file in java. You can delete the file or folder, java File class provide two methods.

Ads

How to delete file in java ?

In this section we will learn how to write a program to delete a file in java. You can delete the file or folder, java File class provide two methods:

delete(path) : This method delete the file or throw an exception if file not deleted. delete() is a static method, to delete a directory then directory should be empty.

deleteIfExists(path) : This method also delete file but if file does not exist then it will not throw an exception.

Now, here is the code to delete a file in java.

import java.io.File;
 
public class DeleteFile
{
    public static void main(String[] args)
    {	
    	try{
 
    		File files = new File("C://Documents and Settings//satya//Desktop//shashi//coreJavaExample//DeleteFile//text.txt");
 
    		if(files.delete())
                                             {
    			System.out.println("File  is deleted!");
    		             }   else
                                                      {
    			System.out.println("Deletion  is failed.");
    		                    }
 
    	}catch(Exception e){
 
    		e.printStackTrace();
 
    	}
 
    }
}

Output : After compiling and executing the above program

Download SourceCode

Advertisements

Share on Google+Share on Google+

How to delete file in java ?

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

Advertisements

Ads
 

Discuss: How to delete file in java ?  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0

Ads

 

Ads