The Wayback Machine - https://web.archive.org/web/20240910201415/https://www.geeksforgeeks.org/delete-file-using-java/
Open In App

Delete a File Using Java

Last Updated : 19 Sep, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Java provides methods to delete files using java programs. On contrary 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. 

Methods used to delete a file in Java: 

1. Using java.io.File.delete() function: Deletes the file or directory denoted by this abstract pathname. 

Syntax: 

public boolean delete()

Returns: It returns true if and only if the file or the directory is successfully deleted; false otherwise

Java




// Java program to delete a file
import java.io.*;
 
public class Test {
    public static void main(String[] args)
    {
        File file
            = new File("C:\\Users\\Mayank\\Desktop\\1.txt");
 
        if (file.delete()) {
            System.out.println("File deleted successfully");
        }
        else {
            System.out.println("Failed to delete the file");
        }
    }
}


Output: 

File deleted successfully

2. Using java.nio.file.files.deleteifexists(Path p) method defined in Files package: 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.

Java




// Java program to demonstrate delete using Files class
 
import java.io.IOException;
import java.nio.file.*;
 
public class Test {
    public static void main(String[] args)
    {
        try {
            Files.deleteIfExists(
                Paths.get("C:\\Users\\Mayank\\Desktop\\
            445.txt"));
        }
        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.");
        }
 
        System.out.println("Deletion successful.");
    }
}


Output: 

Deletion successful.



Previous Article
Next Article

Similar Reads

Java program to delete certain text from a file
Prerequisite : PrintWriter , BufferedReader Given two files input.txt and delete.txt. Our Task is to perform file extraction(Input-Delete) and save the output in file say output.txt Example : Naive Algorithm : 1. Create PrintWriter object for output.txt 2. Open BufferedReader for input.txt 3. Run a loop for each line of input.txt 3.1 flag = false 3
3 min read
Java program to delete duplicate lines in text file
Prerequisite : PrintWriter , BufferedReader Given a file input.txt . Our Task is to remove duplicate lines from it and save the output in file say output.txt Naive Algorithm : 1. Create PrintWriter object for output.txt 2. Open BufferedReader for input.txt 3. Run a loop for each line of input.txt 3.1 flag = false 3.2 Open BufferedReader for output.
3 min read
How to Execute SQL File with Java using File and IO Streams?
In many cases, we often find the need to execute SQL commands on a database using JDBC to load raw data. While there are command-line or GUI interfaces provided by the database vendor, sometimes we may need to manage the database command execution using external software. In this article, we will learn how to execute an SQL file containing thousand
5 min read
How to Convert a Kotlin Source File to a Java Source File in Android?
We use Android Studio to translate our Java code into Kotlin while transitioning from Java to Kotlin. But what if we need to convert a Kotlin file to its Java equivalent? We'll examine how to convert a Kotlin source file to a Java source file in this blog. Let's get this party started. Because of its interoperability with Java, Kotlin grew at an ex
2 min read
StringBuffer delete() Method in Java with Examples
The java.lang.StringBuffer.delete() is an inbuilt method in Java which is used to remove or delete the characters in a substring of this sequence. The substring starts at a specified index start_point and extends to the character at the index end_point. Syntax : public StringBuffer delete(int start_point, int end_point) Parameters : The method acce
3 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 the last character of the substring to be removed fr
3 min read
Files delete() method in Java with Examples
The delete() method of java.nio.file.Files help us to delete a file located at the path passed as a parameter. This method may not be atomic with respect to other file system operations. If the file is a symbolic link then the symbolic link itself, not the final target of the link, is deleted. If the file is a directory then this method will delete
3 min read
Performing Database Operations in Java | SQL CREATE, INSERT, UPDATE, DELETE and SELECT
In this article, we will be learning about how to do basic database operations using JDBC (Java Database Connectivity) API in Java programming language. These basic operations are INSERT, SELECT, UPDATE, and DELETE statements in SQL language. Although the target database system is Oracle Database, the same techniques can be applied to other databas
6 min read
java.nio.file.attribute.FileTime Class in Java
The java.nio.file.attribute.FileTime class is used to get a value representing this file's timestamp i.e, the time when this file was last modified, accessed, or created. Class Declaration: public final class FileTime extends Object implements Comparable<FileTime>Methods: MethodDescriptioncompareTo(FileTime other)This method compares the valu
2 min read
java.nio.file.SimpleFileVisitor Class in Java
The java.nio.file.SimpleFileVisitor Class is used to visit all the files in a directory and to re-throw I/O exceptions whenever an I/O error occurs. Class declaration : public class SimpleFileVisitor<T> extends Object implements FileVisitor<T>Constructor: protected SimpleFileVIsitor(): Creates a new object of SimpleFileVisitor class.Met
3 min read
java.nio.file.Paths Class in Java
java.nio.file.Paths class contains static methods for converting path string or URI into Path. Class declaration : public final class Paths extends ObjectMethods: MethodDescriptionget(String first, String... more) This method converts a path string, or a sequence of strings that when joined form a path string, to a Path. get(URI uri) This method co
2 min read
java.nio.file.spi.FileTypeDetector Class in Java
java.nio.file.spi.FileTypeDetector Class extends java.lang.Object Class. FileTypeDetector Class contain method to know about the content type of given file. Class declaration: public abstract class FileTypeDetector extends ObjectConstructor: ConstructorDescriptionprotected FileTypeDetector()It is used the creation of a new object of FileTypeDetecto
2 min read
java.nio.file.LinkPermission Class in Java
The java.nio.file.LinkPermission class handles permissions for link creation operations. The permission allowed by these class are as follows: Permission name What permission allows Risk of granting this permission hard This permission allows adding an existing file to a directory. This operation is also known as creating a hard link. The attacker
3 min read
java.nio.file.FileStore Class in Java
Java.nio.file is a package in java that consists of the FileStore class. FileStore class is a class that provides methods for the purpose of performing some operations on file store. FileStore is a class that extends Object from java.lang package. And few methods the FileStore class can inherit from java.lang.Object package is clone(), equals(), fi
4 min read
java.nio.file.FileSystem class in java
java.nio.file.FileSystem class provides an interface to a file system. The file system acts as a factory for creating different objects like Path, PathMatcher, UserPrincipalLookupService, and WatchService. This object help to access the files and other objects in the file system. Syntax: Class declaration public abstract class FileSystem extends Ob
4 min read
java.nio.file.FileSystems Class in Java
java.nio.file.FileSystems class acts as a factory for creating new file systems. This class provides methods for creating file systems. This file system act as factories for creating different objects like Path, PathMatcher, UserPrincipalLookupService, and WatchService. This object helps to access the files and other objects in the file system. Syn
3 min read
java.nio.file.attribute.AclEntry Class in Java
ACL entries are Examined by this class is validating on the ACL model declared in RFC 3530: Network File System i.e.(NFS) version of 4th Protocol and having four components within it as follows characteristics as follows: This type of component are determining if the entry grants or denies its accessingThe principal component is generally known as
3 min read
Java.io.File Class in Java
Java File class is Java's representation of a file or directory pathname. Because file and directory names have different formats on different platforms, a simple string is not adequate to name them. Java File class contains several methods for working with the pathname, deleting and renaming files, creating new directories, listing the contents of
6 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 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 a database using sqlyog and create some tables in
2 min read
Size of file on the Internet using Java
To get the size of file from server first you need to connect to the server using URL and HttpURLConnection Class. To get the size of file we use getContentLength() method. As the size of file can be too large we use BigInteger class. You cannot use integer datatype as it can generate an error in case the size of file is greater than 2Gb. To know m
2 min read
Creating a Cell at specific position in Excel file using Java
Apache POI is an open-source java library to create and manipulate various file formats based on Microsoft Office. Using POI, one should be able to perform create, modify and display/read operations on the following file formats/ it can be used to create a cell in a Given Excel file at a specific position. Apache POI is an API provided by the Apach
2 min read
Reading a CSV file in Java using OpenCSV
A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in column by column, and split it by a separator (e.g normally it is a comma “, ”). OpenCSV is a CSV parser library for Java. OpenCSV supports all the basic CSV-type operations you are want to do. Java 7 is currently the minimum supported version for OpenCSV. Java lang
7 min read
Writing a CSV file in Java using OpenCSV
A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in a column by column, and split it by a separator (e.g normally it is a comma “, ”). OpenCSV is a CSV parser library for Java. OpenCSV supports all the basic CSV-type operations you are want to do. Java 7 is currently the minimum supported version for OpenCSV. Java la
5 min read
Creating Sheets in Excel File in Java using Apache POI
Apache POI is an open-source java library to create and manipulate various file formats based on Microsoft Office. Using POI, one should be able to perform create, modify and display/read operations on the following file formats. For Example, java doesn’t provide built-in support for working with excel files, so we need to look for open-source APIs
3 min read
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. Implementation: Convert a String into a byte array and write it
3 min read
Java program to store a Student Information in a File using AWT
Swing is a part of the JFC (Java Foundation Classes). Building Graphical User Interface in Java requires the use of Swings. Swing Framework contains a large set of components which allow a high level of customization and provide rich functionalities, and is used to create window-based applications. Java swing components are lightweight, platform-in
4 min read
How to Write JSON Array to CSV File using Java?
We will see how to read a JSONArray from a JSON file and write the contents to a CSV file using Java. JavaScript Object Notation (JSON) is a standard text-based format for representing structured data that is based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to
3 min read
How to Write Data from Excel File into a HashMap using Java and Apache POI?
Apache POI is an open-source java library to create and manipulate various file formats based on Microsoft Office. Using POI, one should be able to perform create, modify and display/read operations on the following file formats. For Example, Java doesn’t provide built-in support for working with excel files, so we need to look for open-source APIs
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 access to customer information, emails, and other
3 min read
Practice Tags :