Delete File – Java IO File.delete()

Problem Statement:

How to Delete File in Java?

Delete File in Java

Delete File in Java

Description

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

package com.stixs.java.io;

import java.io.File;

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.");
      }
   }
}

Output

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

Reference

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

http://docs.oracle.com/javase/8/docs/api/java/io/File.html

——————————————————————————–

You may also like this

——————————————————————————–

About TechnoStixs.com

Delete File in Java

TechnoStixs.com 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,826 total views, 2 views today

Add comment