Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Delete a File Using Java
Next article icon

Delete a File Using Java

Last Updated : 10 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Java provides methods to delete files programmatically. In contrast to normal delete operations in any operating system, files being deleted using the Java program are deleted permanently without being moved to the trash/recycle bin. 

Example: A basic program to delete the file from a static path.

Java
// Java program to delete a file import java.io.*;  public class DeleteMethod  {     public static void main(String[] args)     {       	// Using Path( Specific File )         File file = new File("C:\\FileHandling\\Delete\\test.txt");        	// Delete the File         if (file.delete()) {             System.out.println("File deleted successfully");         }         else {             System.out.println("Failed to delete the file");         }     } } 

Output:

Delete File

Methods to Delete File in Java

There are two methods which could help us to remove the File using Java as mentioned below:

  1. java.io.File.delete() Method
  2. java.nio.file.files.deleteifexists(Path p) Method

1. Using java.io.File.delete() Method

This method deletes the file or directory denoted by this abstract path name. 

Syntax: 

public boolean delete()

Returns: It returns true, if and only if the file or the directory is successfully deleted.

Example:

Java
// Delete a file using // java.io.File.delete() Method import java.io.*;  public class DeleteMethod  {     public static void main(String[] args) throws IOException     {         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));          System.out.print("Enter the Path : ");                  // Reading File name         String path = br.readLine();          File file = new File(path);          if (file.delete()) {             System.out.println("File deleted successfully");         }         else {             System.out.println("Failed to delete the file");         }     } } 

Output: 

Output


2. Using java.nio.file.files.deleteifexists(Path p) Method

This method deletes a file if it exists. It also deletes a directory mentioned in the path only if the directory is empty. 

Syntax:

public static boolean deleteIfExists(Path path) throws IOException

  • Parameters: path - the path to the file to delete
  • Returns: It returns true if the file was deleted by this method; false if it could not be deleted because it did not exist.

Throws: 

  • DirectoryNotEmptyException - if the file is a directory and could not otherwise be deleted because the directory is not empty (optional specific exception)
  • IOException - if an I/O error occurs.

Example:

Java
// Delete a file using // java.nio.file.files.deleteifexists(Path p) method import java.io.*; import java.nio.file.*; import java.util.Scanner;  public class DeleteUsingFileClass  {     public static void main(String[] args)     {       	// Scanning for file path       	Scanner scn = new Scanner(System.in);              	// Checking the path         try {           	String str;       		str = scn.nextLine();                        Files.deleteIfExists(Paths.get(str));         }       	// Exceptions         catch (NoSuchFileException e) {             System.out.println("No such file/directory exists");         }         catch (DirectoryNotEmptyException e) {             System.out.println("Directory is not empty.");         }         catch (IOException e) {             System.out.println("Invalid permissions.");         }        	// Successful Execution         System.out.println("Deletion successful.");          scn.close();     } } 

Output: 

Delete Using File Class

Next Article
Delete a File Using Java

M

Mayank Kumar
Improve
Article Tags :
  • Java
  • Computer Science Fundamentals
  • Java-Library
  • Java-I/O
  • java-file-handling
Practice Tags :
  • Java

Similar Reads

    Convert byte[] array to File using Java
    As we know whenever it comes to writing over a file, write() method of the File class comes into play but here we can not use it in order to convert that byte into a file. In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementatio
    3 min read
    Encrypt and Decrypt String File Using Java
    In the field of cryptography, encryption is the process of turning plain text or information into ciphertext, or text that can only be deciphered by the intended recipient. A cipher is a term used to describe the encryption algorithm. It secures communication networks and aids in preventing illegal
    3 min read
    How to Read a File using Applet?
    In this article, we will learn how to read the content of the file using Java and display those contents using Applet. Approach UsedThe user should type the name of the file in the input field that asks for the filename in the output applet window. If the file is already present, it will display the
    2 min read
    Delete Contents From Table Using JDBC
    JDBC(Java Database Connectivity) is a standard API(application interface) between the java programming language and various databases like Oracle, SQL, PostgreSQL, etc. It connects the front end(for interacting with the users) with the backend(for storing data). Approach: 1. CREATE DATABASE: Create
    2 min read
    StringBuilder delete() in Java with Examples
    The delete(int start, int end) method of StringBuilder class removes the characters starting from index start to index end-1 from String contained by StringBuilder. This method takes two indexes as a parameter first start represents index of the first character and endIndex represents index after th
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences