Sunday, July 29, 2012

Delete File using Java

In continuation to my last post, Creating a File in Java, I am writing this post to show how to delete a file. It's very simple, you just use the delete() method of the File class and done. The method returns a boolean, true if the file is successfully deleted otherwise false. Here is an example:


package home.flicker.java.io.file;

import java.io.File;

/**
 * @author fLiCkEr
 * Example to show how to delete a file.
 */
public class FileDeletion {

  public static void main(String[] args) {
    try {
      File fileToDelete = new File("test.txt");
               if (fileToDelete.delete()) {
System.out.println("File deleted!!!");
      } 
      else {
System.out.println("Can't delete file!!!");
      }
    } catch (Exception e) {
       System.out.println("Error deleting file: " + e.getMessage());
    }
  }
}


No comments:

Follow by Email