Delete File – Java IO File.delete()

Problem Statement:

How to Delete File in Java?

Delete File in Java

Delete File in Java


To delete file in java, we have to use File.delete() method of File class passing the new instance of file pathname as shown below.  This method returns true if delete operation is successful and returns false if the delete operation fails. If the file doesn’t exist, the delete() methods fails..

Sample Code to delete file in java



public class STXDeleteFileInJava {
   public static void main(String[] args) {

      File file = new File("c:\\samplefile.txt");

      if (file.delete()) {
         System.out.println("STXDeleteFileInJava: " + file.getName() + " was deleted!");
      } else {
         System.out.println("STXDeleteFileInJava: Delete operation failed.");


Case 1: There should be a fail named technostixs.txt at c:\\technostixs\\java path.

STXDeleteFileInJava: samplefile.txt was deleted!

Case 2 : If the file samplefile.txt doesnot exist, the delete() methods fails.

STXDeleteFileInJava: Delete operation failed.

Java API used to delete file in java

Delete File in Java

Delete File in Java


Refer below path to get the complete details about Java IO File class.


You may also like this



Delete File in Java is a dedicated weblog for Java/J2EE and web developers. We take pride in our work. Every publication is carefully analyzed, written and tested to ease the understanding of the topic or subject.

We cover Java Core Technologies, eCommerce, J2EE Frameworks, Web Service, Build Tools, Unit Test Frameworks and Others.


1,880 total views, 2 views today

Add comment