Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Beginners How to delete file in java ?

 
 

Share on Google+Share on Google+

How to delete file in java ?

Advertisement
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.

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

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  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.

Posted on: May 16, 2013

Related Tutorials

Discuss: How to delete file in java ?  

Post your Comment


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