Java Examples - Delete a file


Advertisements


Problem Description

How to delete a file?

Solution

This example shows how to delete a file using delete() method of File class.

import java.io.*;

public class Main {
   public static void main(String[] args) { 
      try {
         BufferedWriter out = new BufferedWriter (new FileWriter("filename"));
         out.write("aString1\n");
         out.close();
         boolean success = (new File("filename")).delete();
         
         if (success) {
            System.out.println("The file has been successfully deleted"); 
         }
         BufferedReader in = new BufferedReader(new FileReader("filename"));
         String str;
         
         while ((str = in.readLine()) != null) {
            System.out.println(str);
         }
         in.close();
      }catch (IOException e) {
         System.out.println("exception occoured"+ e);
         System.out.println("
            File does not exist or you are trying to read a file that has been deleted");
      }
   }
}

Result

The above code sample will produce the following result.

The file has been successfully deleted
exception occouredjava.io.FileNotFoundException:
filename (The system cannot find the file specified)
File does not exist or you are trying to read a 
file that has been deleted

The following is another sample example of delete a file in Java

import java.io.File;

public class DeleteFileExample { 
   public static void main(String[] args) { 
      try { 
         File file = new File("C:\\Users\\TutorialsPoint7\\Desktop\\abc.txt");
         if(file.delete()) { 
            System.out.println(file.getName() + " is deleted!");
         } else {
            System.out.println("Delete operation is failed.");
    		}
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

The above code sample will produce the following result.

abc.txt is deleted!

java_files.htm

Advertisements