delete file in java program

The delete() method of File class is used to delete the existing file in java. It returns true if the specified File deleted successfully otherwise returns false.

Example:

package com.w3spoint;
 
import java.io.File;
 
public class DeleteFileTest {
  public static void main(String args[]){
      try {
    	//Specify the file name and path
     	 File file = new File("D:/Test files/test.txt");
         //Delete the specified file 
     	 if(file.delete()){
     	    System.out.println("File "+file.getName() + " is deleted.");
          }else{
     	    System.out.println("File "+file.getName() + " is not deleted.");
     	  }
      } catch (Exception e) {
          e.printStackTrace();
      } 
  }
}

Output:

Stored data in temporary file.
File test.txt is deleted.

Download this example.

Content Protection by DMCA.com
Please Share