Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Delete a file using java.nio.file.files.deleteifexists(Path p)
3.
Delete a file using  java.io.File.delete() function
4.
Frequently Asked Questions
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Delete a file using Java

Author Mehak Goel
0 upvote

Introduction

In this blog, we’ll learn how to delete a file or directory in Java. It provides methods for deleting files from programs. Unlike typical delete operations in any operating system, files removed with the java program are permanently erased and does not go to the trash or the recycling bin.

The article demonstrates two ways of deleting a File in java:

  • Delete file using java.nio.file.files.deleteifexists(Path p)
  • Delete file using java.io.File.delete() function

Delete a file using java.nio.file.files.deleteifexists(Path p)

The  java.nio.file.files.deleteifexists(Path p) method also deletes the file or directory defined by abstract pathname. Generally, we use this method when we have to delete a temporary file. It is not possible to cancel a request once it has been made. As a result, this method should be used with extra caution.

CODE:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
    public static void main(String[] args) {

        try {
            // this line creates a file object
            Path filePath = Paths.get("JavaFile.java");

            // deletes the file and returns true if the file is deleted, otherwise false
            boolean isFileDeleted = Files.deleteIfExists(filePath);
            if (isFileDeleted) {
                System.out.println("JavaFile.java is successfully deleted.");
            } else {
                System.out.println("File doesn't exist. Can’t delete the file which does not exist!");
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
    }
}

 

Output:

 

The delete() function of the File class was used to delete the file named JavaFile.java in the example given above.
If the file is present, the message JavaFile.java has been successfully deleted will be shown. Otherwise, the message File doesn't exist. Can’t delete the file which does not exist! is shown.
Try it by yourself on Java Online Compiler.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Delete a file using  java.io.File.delete() function

The File.delete() function of the File class in Java can be used to delete a file. The delete() method removes the file or directory specified by the abstract path-name from the system.

If the path-name is a directory, it must be empty in order to be deleted.

CODE:

import java.io.File;
public class Main {
    public static void main(String[] args) {

        //this line creates a file object
        File file = new File("JavaFile.java");

        // this line deletes the file and returns true if deleted successfully, otherwise false.
        boolean isFileDeleted = file.delete();
        if (isFileDeleted) {
            System.out.println("JavaFile.java is successfully deleted.");
        } else {
            System.out.println("File doesn't exit");
        }
    }
}

 

Output:

Here, we've used the deleteIfExists() method of java.nio.file.Files class. The method deletes the file if it is present in the specified path.

Also see, Duck Number in Java

Frequently Asked Questions

  1. What is polymorphism in Java?
    Polymorphism means "many forms," and it happens when there are multiple classes that are connected to each other through inheritance. As we discussed in the last chapter, Inheritance allows us to inherit attributes and methods from another class. Polymorphism uses these methods to accomplish a variety of objectives.
     
  2. What is multithreading in Java?
    Multithreading is a Java feature that allows the execution of two or more portions of a program at the same time to maximize Central processing unit efficiency. A thread is a component of such a program. As a result, threads are lightweight processes within a process.
     
  3. What are the two types of Java programs?
    There are two types of Java programs:
    → Java Stand-Alone Applications 
    → Java Applets

Conclusion

In this blog, we have discussed how to delete a file or directory in Java. Along with a few more important terminologies with its code.

We hope that this blog has helped you enhance your knowledge regarding how to delete a file using Java and if you would like to learn more, check out our articles on the link. Do upvote our blog to help other ninjas grow. 

Happy Coding!

Previous article
How to write on files in java
Next article
File Permissions
Live masterclass