How to delete files in Java?

In this tutorial you will how to delete files in Java?

Ads

Delete a File using File Class Object

     

Delete a File using File Class Object

In this section, you will learn how to delete a file.  For deleting a file, first we, creates a new File instance by converting the given pathname string into an abstract pathname using object of the File class. Secondly, we use the delete() function to delete the file.

Given below example will give you a clear idea :

Example :

import java.io.*;

public class DeleteFile {
public static void main(String[] args) {
boolean success = (new File("file.txt")).delete();
if (success) {
System.out.println("The file has been successfully deleted");
} else {
System.out.println("File Doesn't Exist");
}
}
}

Output :

If file deletion operation is successful, it will show :

The file has been successfully deleted   

If file doesn't exist or any occurred in deleting file, it  will show:

Some error occurred    

Download Source Code

Advertisements

Ads
Share on Google+Share on Google+

How to delete files in Java?

Posted on: February 19, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

 

Discuss: How to delete files in Java?  

Post your Comment


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

Ads

 

Ads