beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

How to delete file in Java – delete() Method

By Chaitanya Singh | Filed Under: Java I/O

In this tutorial we will see how to delete a File in java. We will be using the delete() method for file deletion.

public boolean delete()

This method returns true if the specified File deleted successfully otherwise it returns false.

Here is the complete code:

import java.io.File;
public class DeleteFileJavaDemo
{
   public static void main(String[] args)
   {	
      try{
         //Specify the file name and path
    	 File file = new File("C:\\myfile.txt");
         /*the delete() method returns true if the file is
          * deleted successfully else it returns false
          */
    	 if(file.delete()){
    	    System.out.println(file.getName() + " is deleted!");
         }else{
    	    System.out.println("Delete failed: File didn't delete");
    	  }
       }catch(Exception e){
           System.out.println("Exception occurred");
    	   e.printStackTrace();
    	}
    }
}

Output:

myfile.txt is deleted!

Reference:
delete() – Javadoc

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap