Open In App

How to Delete Temporary File in Java?

Last Updated : 05 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In java, we have a java.io package that provides various methods to perform various operations on files/directories. 

Temporary files are those files that are created for some business logic or unit testing, and after using these files you have to make sure that these temporary files should be deleted. If you forget to delete these temporary files then this will take extra space while executing which is not efficient for your application.

To Create Temporary File:- The file class which is present in the java.io package has createTempFile() method that will take two arguments i.e. name of the file(prefix) and extension (suffix) of the temp file. Provide an abstract path at which you need to create the temporary file.

Java




// Create temp file
 
import java.io.File;
import java.io.IOException;
public class tempFile {
    public static void main(String args[])
        throws IOException
    {
        // name of the file
        String prefix = "TempFile";
 
        // extension of the file
        String suffix = ".txt";
 
        // Creating a File object for directory
        File directoryPath = new File(
            "/home/krishna/Desktop/java/junior/");
 
        // Creating a temp file
        File.createTempFile(prefix, suffix, directoryPath);
        System.out.println(
            "Temp file created at the specified path");
    }
}


Output: 

Temporary file has been created in the specified path

There are two ways you can delete an existing temporary file.

A. Delete when JVM exits: 

You can use deleteOnExit() method to delete an existing file only when your application completes. If your code terminates abnormally then keep in mind that your temporary file has not been deleted yet and once you have requested for the delete operation then you can’t cancel afterwards.

Java




// Delete File when JVM Exists
 
import java.io.File;
import java.io.IOException;
 
public class tempFile {
    public static void main(String[] args)
    {
        File temp;
        try {
            // name of the file and extension
            temp = File.createTempFile("TempFile", ".txt");
 
            // Delete when JVM exits
            temp.deleteOnExit();
        }
        // If not found any temporary file
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}


 B. Delete the file immediately: 

We can delete a temporary file with the use delete() method.

Java




// Delete file using delete() method
 
import java.io.File;
import java.io.IOException;
 
public class tempFile {
    public static void main(String[] args)
    {
        File temp;
        try {
            temp
                = File.createTempFile("myTempFile", ".txt");
 
            // Perform other operations
            // Delete the file immediately
            temp.delete();
        }
        // If not found the temporary file
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}




Similar Reads

Java Program to Create a Temporary File
A File is an abstract path, it has no physical existence. It is only when "using" that File that the underlying physical storage is hit. When the file is getting created indirectly the abstract path is getting created. The file is one way, in which data will be stored as per requirement. Type of File .txt.tmp (Default File Type)Primary, in order to
5 min read
Create a Temporary File in Java
In Java, we can create a temporary file using an existing method known as File.createTempFile() method which creates a new empty file on the specified directory. The createTempFile() function creates a temporary file in a given directory (if the directory is not mentioned then a default directory is selected), the function generates the filename by
4 min read
Java Program to Write Data to Temporary File
A Temporary file or a Temp file is a file that is created in order to hold information for some time while a file is being created or modified. After the successful execution of the program or after the program is closed, the temporary file is deleted. Other advantages of having a temporary file are that it helps in storing and moving data, managin
3 min read
How to set Temporary and Permanent Paths in Java
If the Java source file is inside the jdk/bin folder,path is not required to be set because the tools like javac,java are inside the current folder. But if the java source file is outside the jdk/bin folder,path is required to be set in order to execute java source file. There are two ways to set java path: Temporary Permanent Setting Temporary Jav
1 min read
File delete() method in Java with Examples
The delete() function is a part of File class in Java . This function deletes an existing file or directory. If the file is deleted then the function returns true else returns false Function signature: public boolean delete() Syntax: boolean var = file.delete(); Parameters: This method does not accept any parameter. Return Type: The function return
2 min read
Delete a File Using Java
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 den
2 min read
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
Different Ways to Copy Content From One File to Another File in Java
In Java, we can copy the contents of one file to another file. This can be done by the FileInputStream and FileOutputStream classes. FileInputStream Class It is a byte input stream class which helps in reading the bytes from a file. It provides different methods to read the data from a file. FileInputStream fin = new FileInputStream(filename); This
3 min read
Article Tags :
Practice Tags :