×

Java Programs

Java Practice

Java program to delete a file

Problem statement

This program will delete an existing file. There is a method delete() of File class which is used to delete the file and returns true or false, if the file deletes method returns true otherwise false.

Java program to delete a file

In this program. Firstly we are checking file exists or not using the File.exists() method, if the file exits program will move to the file delete code and the file will be deleted using File.delete().

Delete File using Java Program

// Java program to get file size 
// and file path

import java.io.File;

public class ExDeleteFile {
  public static void main(String args[]) {
    final String fileName = "file3.txt";

    //File class object
    File objFile = new File(fileName);

    //check file is exist or not, if exist delete it
    if (objFile.exists() == true) {
      //file exists
      //deleting the file
      if (objFile.delete()) {
        System.out.println(objFile.getName() + " deleted successfully.");
      } else {
        System.out.println("File deletion failed!!!");
      }
    } else {
      System.out.println("File does not exist!!!");
    }
  }
}

Output

    
file3.txt deleted successfully.

Java File Handling Programs »





Comments and Discussions!

Load comments ↻





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