Q:

Java program to delete a file

belongs to collection: Java File Handling Programs

0

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.

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().

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java File Handling Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to copy files... >>
<< Java program to get file size and file path...