HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / I/O / Java Create Temporary File

Java Create Temporary File

Creating a temporary file in Java can be required in many scenarios, but mostly it will happen during unit tests where we don’t want to store the output of the intermediate operations. As soon as the test is finished, we do not need these temp files and we can delete them.

While unit testing using Junit, you can use TemporaryFolder as well. The TemporaryFolder rule allows creation of files and folders that are guaranteed to be deleted when the test method finishes (whether it passes or fails).

1. File.createTempFile()

The createTempFile() is an overloaded method. Both methods create a new empty temporary file. If the target directory argument is not specified, file is created in the the default temporary-file directory specified by the system property java.io.tmpdir.

Both methods will create the file only if there is not file with same name and location that exist before the method is called.

If we want the file to be deleted automatically, use the deleteOnExit() method.

File createTempFile(String prefix, String suffix) throws IOException
File createTempFile(String prefix, String suffix, File directory) throws IOException

Example 1: Creating a temporary file with specific name

public class TemporaryFileExample
{
   public static void main(String[] args)
   {
      File temp;
      try
      {
         temp = File.createTempFile("myTempFile", ".txt");
		 
         System.out.println("Temp file created : " + temp.getAbsolutePath());
      } catch (IOException e)
      {
         e.printStackTrace();
      }
   }
}

Program Output:

Temp file created : C:\Users\admin\AppData\Local\Temp\myTempFile3492283537103788196.txt

2. Files.createTempFile() – Java NIO

This createTempFile() is also an overloaded method. Both methods create a new empty temporary file.

If we want the file to be deleted automatically, open the file with DELETE_ON_CLOSE option so that the file is deleted when the appropriate close() method is invoked.

Path createTempFile(String prefix, String suffix, FileAttribute<?>... attrs)
Path createTempFile(Path dir, String prefix, String suffix, FileAttribute<?>... attrs)

Example 2: Creating a temporary file in temp folder

In the given example, the created temporary file will be deleted when the program exits.

public class TemporaryFileExample
{
   public static void main(String[] args)
   {
      try
      {
         final Path path = Files.createTempFile("myTempFile", ".txt");
         System.out.println("Temp file : " + path);
         
         //Delete file on exit
         path.toFile().deleteOnExit();
         
      } catch (IOException e)
      {
         e.printStackTrace();
      }
   }
}

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Himansu

    November 10, 2014

    Hi Pankaj,

    The only problem which i face while using this api are the random number which get added while creating the file.

    [File Name] **** Random Number **** [File Extension]

    Is there any way i can handle the name of the temporary file in my way, as certain use case need the file name in

    advance.

    Regards,
    Himansu

    • Lokesh Gupta

      November 11, 2014

      You can use “getName()” method to get the actual file name created.

Comments are closed on this article!

Search Tutorials

Java IO

  • Java IO Introduction
  • Java How IO works?
  • Java IO vs NIO
  • Java Create File
  • Java Write to File
  • Java Append to File
  • Java Read File
  • Java Read File to String
  • Java Read File to Byte[]
  • Java Make File Read Only
  • Java Copy File
  • Java Copy Directory
  • Java Delete Directory
  • Java Current Working Directory
  • Java Read/Write Properties File
  • Java Read File from Resources
  • Java Read File from Classpath
  • Java Read/Write UTF-8 Data
  • Java Check if File Exist
  • Java Create Temporary File
  • Java Write to Temporary File
  • Java Delete Temporary File
  • Java Read from Console
  • Java Typesafe input using Scanner
  • Java Password Protected Zip
  • Java Unzip with Subdirectories
  • Java Generate SHA/MD5
  • Java Read CSV File
  • Java InputStream to String
  • Java String to InputStream
  • Java OutputStream to InputStream
  • Java InputStreamReader
  • Java BufferedReader
  • Java FileReader
  • Java LineNumberReader
  • Java StringReader
  • Java FileWriter
  • Java BufferedWriter
  • Java FilenameFilter
  • Java FileFilter

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)