EaseUS Data Recovery Wizard 11582 Reviews

How to Use Java Delete File if Exists (in Four Ways)

This post shows you how to use Java to delete files and directories. There are 4 ways to delete files and folders on Windows. After Java deletes files that exist, you can also retrieve them via EaseUS Data Recovery Wizard.

 Download for Win Recovery Rate 99.7%
 Download for Mac Trustpilot Rating 4.7

Table of Contents

Overview: What Is Java Delete File

You might occasionally run into a file you can't delete normally. In that case, you must first understand the cause if you want to solve the issue. Usually, the main cause is that the file is encrypted or locked. If not, a virus needs to be considered.

Don't worry. You can use Java to delete file if exists as long as you know Java language. Even if you are a novice to Java programs, you can quickly get the 4 methods mentioned in this article.

What is Java? Sun Microsystems introduced Java in 1995, a programming language and computing platform. It has grown from its modest origins to power a significant portion of today's digital world by offering the solid foundation upon which numerous services and applications are developed. Java is still used in cutting-edge goods and digital services that are being developed for the future.

Besides, you can use Java to set PC instructions that tell your computers how to perform different tasks. When you want to delete specific files, For instance: 

  • ⏰Delete files or directories older than x days automatically.
  • 🗒️Delete files with spaces on the end.
  • 🪄Delete files that do not match criteria in bulk.

4 Ways: How to Delete Files in Java

⚠️You can use Java to delete links, directories, and files. With symbolic links, the link itself is removed rather than the target. As for directories, the deletion must succeed with an empty directory.

Before learning the 4 ways, you could watch the following tutorial video first. The instructions for Java to delete files by running specific scripts are included in the video.

  • 00:08 - Introduction
  • 00:33 - How to create a new Java project in Eclipse
  • 00:53 - How to create a class in eclipse
  • 01:51 - How to create a variable in Java programming language

If you are still confused, please read the 4 solutions below.

  1. 1. Use the Delete( ) Method to Remove Files
  2. 2. Try Delete(Path) Method for Java
  3. 3. Delete a Folder and its Subfolders
  4. 4. How Java Delete Directory

Method 1. Use the Delete( ) Method to Remove Files

When using the conventional File IO java.io.*, you can delete a file using the File.delete( ) method returns a boolean value (true if the file was successfully deleted, false otherwise).

To delete files in Java, try the following command:

import java.io.File;

public class DeleteFileExample1 {
    public static void main(String[] args) {
    // File to be deleted
    File file = new File("foo.txt");

    // Delete file
    boolean isDeleted = file.delete();

    if(isDeleted) {
      System.out.println("File deleted successfully");
     } else {
      System.out.println("File doesn't exist");


How to Use CMD Delete File/Folder [Windows 11]

Command Prompt is a command-line interpreter application also known as cmd.exe or cmd. It can only be used in Windows operating system. Read more >>

Method 2. Try the Delete(Path) Method for Java to Delete Files

The delete(Path) method either successfully deletes the file or throws an error if it cannot. For instance, a NoSuchFileException is raised if the file does not exist. To find out why the delete failed, you can capture the exception as follows:

try {
} catch (NoSuchFileException x) {
    System.err.format("%s: no such" + " file or directory%n", path);
} catch (DirectoryNotEmptyException x) {
    System.err.format("%s not empty%n", path);
} catch (IOException x) {
    // File permission problems are caught here.

Method 3. Delete a Folder and its Subfolders

You can also delete a folder and its subfolders. However, the folders must be empty:

import java.io.File; 

public class DeleteFolder {
  public static void main(String[] args) { 
    File myObj = new File("C:\\Users\\MyName\\Test"); 
    if (myObj.delete()) { 
      System.out.println("Deleted the folder: " + myObj.getName());
    } else {
      System.out.println("Failed to delete the folder.");

Force Delete a Folder

How to Force Delete a Folder or File in Windows 10/Windows 11

You can force delete folders or files in CMD, use force delete folder software, change ownership, or force delete folder in Safe Mode. Read more >>

Method 4. How Java Delete Directory

To delete the directory, firstly, you should provide the path of the directory and prepare to delete all the files and subfolders.

import java.io.File;
class DeleteDirectory {
    // function to delete subdirectories and files
  public static void deleteDirectory(File file)
    // store all the paths of files and folders present
    // inside directory
    for (File subfile : file.listFiles()) {
    // if it is a subfolder,e.g Rohan and Ritik,
    //  recursively call function to empty subfolder
       if (subfile.isDirectory()) {
    // delete files and empty subfolders

How to Delete Files

How to Delete Files, Folders, and Directories in Linux Using Command

How do I delete a file in Linux using Terminal? This article explains how to remove files, folders, or directories in Linux Terminal. Read more >>

We have learned 4 different ways to use Java to delete files and directories. After that, don't forget to mark this passage by sharing it on Facebook, Twitter, or SNS.


Bonus Tip: How to Recover Lost Files Deleted by Java

If you were trying the scripts above but accidentally deleted some system files or folders, you might have removed the files necessary for Java commands. If that happens, you ought to recover deleted files from Windows 10.

You may also unintentionally delete your important private files and folders and have no idea of how to restore permanently deleted items. Fortunately, using the EaseUS Data Recovery Wizard, you may quickly return these necessary items.

EaseUS Data Recovery Wizard

  • Recover lost or deleted files, documents, photos, audio, music, and emails effectively
  • Recover deleted file from flash drive, emptied recycle bin, memory card, digital camera, HDD, and SSDs.
  • Support data recovery for sudden deletion, formatting, hard drive corruption, virus attack, system crash under different situations
 Download for Win Recovery Rate 99.7%
 Download for Mac Trustpilot Rating 4.7

Check the steps and learn how to use the software to recover deleted files:

Step 1. Select the location to scan

Choose the specific device and drive where you have permanently deleted files using Shift delete or emptying recycle bin. Then, click the "Scan" button to find lost files.

select a location and click scan

Step 2. Check the results

The software will automatically start scanning all over the selected drive. When the scan completes, select the "Deleted Files" and "Other Lost Files" folders in the left panel. Then, apply the "Filter" feature or click the "Search files or folders" button to quickly find the deleted files.

scan permanently deleted files

Step 3. Recover deleted files

Select the deleted files and click "Preview". Next, click "Recover" to save them to another secure location or device.

select files and click recover

To Wrap It up

This article offers you four workable solutions. Most users claim that their issues were resolved after using Method 1. And Method 1 is the one I prefer most. If you have a different solution to this issue that you would want to share with us, please do so; our readers would be very interested in reading it.

Additionally, your PC might function effectively to safeguard your files even deleted by Java with EaseUS Data Recovery Wizard.

 Download for Win Recovery Rate 99.7%
 Download for Mac Trustpilot Rating 4.7

Java Delete File FAQs

Here are 4 additional questions about Java delete files. Check here to see if it has the question you are interested in and find the answers.

1. How to delete a file in Java?

Using the File. delete( ) function of the File class; we can delete a file in Java. The file or directory indicated by the abstract pathname is deleted by the delete( ) method. If the pathname is a directory, it must be empty to be deleted.

2. How to force delete folder Windows open in another program?

You can: To avoid getting the File in Use error when removing folders:

  • Utilize the Task Manager to end the program.
  • Switch off your computer.
  • Using CMD, remove a folder forcibly
  • Use software to erase a folder forcibly.

3. How to delete files older than X days in Windows 11/10 using Storage Sense?

  1. To access Windows Settings, press "Win+I".
  2. Then click Storage Sense under System - Storage.
  3. The Automatic User Content Cleanup button should be toggled.
  4. From the Run Storage Sense menu, select a setting.
  5. The button must be pressed to start Storage Sense.

4. How do I delete multiple files in the command prompt?

The del command allows you to delete individual and group files.

  • 1. Insert a space after you type "del."
  • 2. After that, enter the path for each file you want to remove, making sure to separate each file name with a space.
  • 3. Check that you are typing the correct path before pressing the Enter key.

Was This Page Helpful?

Updated by Jaden

Jaden is one of the editors of EaseUS who lives and works in Chengdu, China. She focuses on topics concerning PCs and Mac data recovery. Jaden is committed to enhancing professional IT knowledge and writing abilities. She is always keen on new and intelligent products.

Read full bio

Product Reviews

TrustScore 4.7 | 323 reviews
  • EaseUS Data Recovery Wizard is a powerful system recovery software, designed to enable you to recover files you’ve deleted accidentally, potentially lost to malware or an entire hard drive partition.

    Read More
  • EaseUS Data Recovery Wizard is the best we have seen. It's far from perfect, partly because today's advanced disk technology makes data-recovery more difficult than it was with the simpler technology of the past.

    Read More
  • EaseUS Data Recovery Wizard Pro has a reputation as one of the best data recovery software programs on the market. It comes with a selection of advanced features, including partition recovery, formatted drive restoration, and corrupted file repair.

    Read More