Java Delete File | Remove | If Exists | Directory with Example

In Application after use of file want a delete a file or director, but how and what are the best way to do it? In this tutorial, we will see the Java Delete File program example and little detail on it. The right way to do coding is very important.

java.io.File.delete()- A Java File delete() method will use to delete files or directory/folder (even empty). It will return boolean true if the file or directory deleted successfully.

Java Delete File Remove If Exists Directory with Example

Some Important Point:

When you are deleting a Java file or Directory, some caution is required.

  • Check file and folder dependency.
  • If Deleting directory then check to contain file using a loop statement.
  • for safety check whether file using or not.

Note: We are considering a File means text, jpg, etc and Directory(folder) means contains many Files or folders or both.

Java Delete File Example Or Java remove the file 

See the example, it will delete a file text file with named “newfile.txt”.

Output: File deleted

See below: Code structure and how to run in gif presentation.

Java Delete File example

Java delete directory Example

In this example, we will cover 2 things first delete a file in java and second How java delete files in a directory.

Here is the file location. Where Doc is a directory having 2 files “img.png” and “test.txt“.

Java delete directory Example

first, need to check whether the file exists or not then run the for loop or for-each loop and get the list of the file inside.

Output: Deleting img.png
Deleting test.txt
Success = true

Question: How to  Java delete the file if exists with the path.

Answer:  for that you just need the same process with a “path+file/directory name”.

File path:

Directory Path:

If you have doubts and suggestions on how to java remove the file, do comment below.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1

Java version 11

All Java Delete File are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.