# Java Program to delete file or directory

Java 8Object Oriented ProgrammingProgramming

The method java.io.File.delete() can be used to delete the file or directory with the required abstract path name. This method requires no parameters and it returns true on the successful deletion of the file or the directory and false otherwise.

A program that demonstrates this is given as follows −

## Example

Live Demo

import java.io.File;
public class Demo {
public static void main(String[] args) {
try {
File file = new File("demo1.txt");
file.createNewFile();
System.out.println("File: " + file);
boolean flag = file.delete();
System.out.println("The File is deleted? " + flag);
} catch(Exception e) {
e.printStackTrace();
}
}
}

The output of the above program is as follows −

## Output

File: demo1.txt
The File is deleted? true

Now let us understand the above program.

The file with the required abstract path name is deleted using the method java.io.File.delete(). Then the boolean value returned by this method is printed. A code snippet that demonstrates this is given as follows −

try {
File file = new File("demo1.txt");
file.createNewFile();
System.out.println("File: " + file);
boolean flag = file.delete();
System.out.println("The File is deleted? " + flag);
} catch(Exception e) {
e.printStackTrace();
}
Published on 25-Feb-2019 12:27:20