English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)/O)

Java Reader/Writer

Java Other Topics

Java program to implement file deletion

Comprehensive Java Examples

In this instance, we will learn how to use the Java File and Files classes to delete files.

Example1Java program to use delete() method to delete a file

import java.io.File;
public static void main(String[] args) {
  try {
    //Path path = Paths.get("JavaFile.java");
    File file = new File("JavaFile.java");
    // boolean value = Files.deleteIfExists(path);
    boolean value = file.delete();
    System.out.println("JavaFile.java has been successfully deleted.");
      else {
    }
    System.out.println("File does not exist");
      catch (Exception e) {
    }
  }
}

In the above example, we used the File class's delete() method to delete the file named JavaFile.java file.

Here, if the file exists, the message is displayedJavaFile.java has been successfully deleted. Otherwise, it will display “ File does not exist.

For more information about files, please visitJava File.

Example2Java program to use deleteIfExists() to delete a file

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public static void main(String[] args) {
  try {
    Create a file object
      //Path path = Paths.get("JavaFile.java");
      Delete File
      //boolean value = Files.deleteIfExists(path);
      if (value) {
      System.out.println("JavaFile.java has been successfully deleted.");
        else {
      }
      System.out.println("File does not exist");
        catch (Exception e) {
      }
    }
      e.getStackTrace();
    }
  }
}

Here, we use the deleteIfExists() method of the java.nio.file.Files class. If the file exists at the specified path, this method will delete the file.

Notejava.nio.file is a package used to handle files in Java.

Comprehensive Java Examples