Home » Java programming language

Java File Class boolean delete() method with Example

Java File Class boolean delete() method: Here, we are going to learn about the boolean delete() method of File class with its syntax and example.
Submitted by Preeti Jain, on July 05, 2019

File Class boolean delete()

  • This method is available in package java.io.File.delete().
  • This method is used to delete file or directory by using delete() method and this method is accessible with the File object.
  • The return type of this method is Boolean i.e. it returns true or false if true that means file is successfully deleted and returns false that means the file is failed to delete.

Syntax:

    boolean delete(){
    }

Parameter(s):

We don't pass any object as a parameter in the method of the File.

Return value:

The return type of this method is Boolean i.e. it returns true or false if true that means file is successfully created else returns false that means the file is failed to delete.

Java program to demonstrate example of delete() method

// import the File class because we will use File class methods
import java.io.File;

// import the Exception class because it may raise an exception 
// when working with files
import java.lang.Exception;

public class DeleteFile {
    public static void main(String[] args) {
        try {
            // Specify the path of file and we use double slashes 
            // to escape '\' character sequence for windows 
            // otherwise it will be considerable as url.
            File file1 = new File("C:\\Users\\computer clinic\\OneDrive\\Articles\\javafiles.txt");
            File file2 = new File("C:\\Users\\computer clinic\\OneDrive\\Articles\\myjav.txt");

            // By using delete() method returns true that's means 
            // file is deleted successfully.
            if (file1.delete())
                System.out.println("File deleted Successfully" + " " + file1.getName());
            else
                System.out.println("File failure of deletion " + file1.getName());

            // By using delete() method returns false that's means 
            // file failure of deletion.
            if (file2.delete())
                System.out.println("File deleted Successfully" + file2.getName());
            else
                System.out.println("File failure of deletion" + " " + file2.getName());

        } catch (Exception e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

Output

D:\Programs>javac DeleteFile.java

D:\Programs>java DeleteFile
File deleted Successfully C:\Users\computer clinic\OneDrive\Articles\javafiles.txt
File failure of deletion C:\Users\computer clinic\OneDrive\Articles\myjav.txt



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.