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
  • 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

Enjoyed this post? Try these related posts

  1. How to read file in Java – BufferedInputStream
  2. How to make a File Read Only in Java
  3. How to read file in Java using BufferedReader
  4. How to write to file in Java using BufferedWriter
  5. How to Copy a File to another File in Java
  6. How to Compress a File in GZIP Format

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 – 2021 BeginnersBook . Privacy Policy . Sitemap