java delete file

Let’s learn java delete file.

java delete file

To delete a file in java delete() method is used of File class.

delete() method deletes the file or directory denoted by this abstract pathname.

If this pathname denotes a directory, then the directory must be empty in order to be deleted. delete() method returns true if and only if the file or directory is successfully deleted; false otherwise.

Here’s the program on delete a file.

import java.io.File;
public class JavaDeleteFile
{
   public static void main(String[] args) 
   {
      try
      {         
         File file = new File("E:\\example.txt");  
         if(file.delete())  
         {
            System.out.println(file.getName() + " file deleted.");  
         }
         else  
         {  
            System.out.println("failed");  
         }
      }  
      catch(Exception ex)  
      {  
         ex.printStackTrace();  
      }
   }
}


Output:

example.txt file deleted


Also read – HashSet in java