How to delete a file or empty directory in java?

Deletes the file or directory, true if  the file or directory is successfully deleted; false otherwise.

  • Delete a File
package com.nourit.javaIO;

import java.io.File;

public class DeleteFile {
  
  public static void main(String[] args) {
    try {

      File file = new File("D:\\nourit.txt");

      if (file.delete()) {
        System.out.println("the Filename:  " + file.getName() + " is deleted!");
      } else {
        System.out.println("Delete operation is failed.");
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Output:

the Filename:  nourit.txt is deleted!

 

  • Delete a Directory
package com.nourit.javaIO;

import java.io.File;

public class DeleteFileDirectory {
  
  public static void main(String[] args) {
    try {

      File file = new File("D:\\nourit.txt");
      //create Directory
      if (file.mkdir()) {
                System.out.println("Directory is created!");
                if (file.isDirectory()) {
                	System.out.println("the Directory:  " + file.getName() + " is deleted!");
                	file.delete();
                }
            } else {
                System.out.println("Failed to create directory!");
            }
      

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Output:

Directory is created!
the Directory:  nourit.txt is deleted!

 

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*