Delete an existing file - Java Program

Q. Write a program to delete an existing file.

Answer:

The java.io.File.delete() method is used to delete the file. The BufferedReader class reads the data from the file.

In this example, we use delete() method, which deletes the file permanently.

DeleteFile.java

import java.io.*;
class DeleteFile
{
     public static void main(String[] args)
     {
          try
          {
               BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("file.txt"));
               bufferedWriter.write("Welcome");
               bufferedWriter.close();
               boolean status = (new File("file.txt")).delete();
               if (status)
               {
                    System.out.println("File deleted successfully");
               }
               BufferedReader bufferedReader = new BufferedReader(new FileReader("file.txt"));
               String str;
               while ((str = bufferedReader.readLine()) != null)
               {
                    System.out.println(str);
               }
               bufferedReader.close();
          }
          catch (IOException ioe)
          {
               System.out.println("File not found");
               ioe.printStackTrace();
          }
     }
}


Output:

file delete