Wednesday, 20 February 2013

How to delete a file with Java

If we want to delete the file located in C:\Test\file.txt
we need this code :
// Import the following in your code...

import java.io.File;

public class FileDeleter  {
public static void main(String args[]) {

File ourFile = new File("C://Test//file.txt ");
      try{
    // Delete the file if exists     
  
            if(ourFile.exists()){
                    ourFile.delete();    

               }
    

  }catch (Exception e){//Catch exception if any
  System.err.println("Error: " + e.getMessage());
         }


}
}

when you run this program it deletes the file.txt

No comments:

Post a Comment