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.8

Page Table of Contents

Updated By

Finley

Written By

Jaden

Updated on

24 July 2024

Min Reading

9 Min

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");
    } 
  } 
}

 
Command

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 {
    Files.delete(path);
} 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.
    System.err.println(x);
}

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()) {
       deleteDirectory(subfile);
    }
    // delete files and empty subfolders
       subfile.delete();
    }
  }

 
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.

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

  • 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

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 "Search for Lost Data" 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 or lost folders in the left panel using the "Path" feature. Then, apply the "Filter" feature or use the search box 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. You can choose a cloud storage, such as OneDrive, Google Drive, etc., and click "Save" to save your recovered files.

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.8

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.
  • Updated by

    Finley is interested in reading and writing articles about technical knowledge. Her articles mainly focus on file repair and data recovery.…
  • Written by

    Jaden is one of the editors of EaseUS, who 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.…
Why Trust EaseUSEditor Reviews

20+

Years of experience

160+

Countries and regions

72 Million+

Downloads

4.8 +

Trustpilot Score

Data Recovery Service

Search