How to delete a file in java

  • by

Using file.delete() method you can delete a file or directory in java. You can delete any file or directory. After deleting file or directory, it will return a boolean value to indicate the delete operation status; true if the file is deleted; false if failed.

Delete a file or directory in java:-                                                                                             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 occurred”+ e);
System.out.println(“File does not exist or you are trying to read a file that has been deleted”);
}
}
}
}

 

Leave a Reply