1. Create file with random name

File file = File.createTempFile(String prefix, String suffix, File parent)
  • Actually create the file on disk and returns the file object
  • Create a file name in this format: prefix + random number + suffix
  • Useful when you need create temporary file on disk

2. Create file with exact name

File file = new File(File parent, String child);
file.createNewFile();
  • Actually create the file on disk and returns true if file get created successfully

  • File name will exactly as pass to child parameter

  • Useful when you need create permanent file on disk

3. Create only file object (in memory)

File file = new File(File parent, String child);
// doesn't create the file on disk until calling createNewFile() method
  • Only create the in memory and not actually on disk
  • Useful when you need just create file object (e.g just to pass it as parameter)

parent parameter can be one of these:

  1. App private directories

    • context.getCacheDir()
    • context.getExternalCacheDir()
    • and ... (full list can be found here)
  2. Public directories

    • Environment.getExternalStorageDirectory()
    • Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES)
    • and ... (full list can be found here)
Answer from Behzad Bahmanyar on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › io › File.html
File (Java Platform SE 8 )
April 21, 2026 - The Files.createTempFile method provides an alternative method to create an empty file in the temporary-file directory.
🌐
GeeksforGeeks
geeksforgeeks.org › java › file-createtempfile-method-in-java-with-examples
File createTempFile() method in Java with Examples - GeeksforGeeks
June 20, 2021 - The createTempFile() function creates a temporary file in a given directory ( if directory is not mentioned then a default directory is selected ), the function generates the filename by using the prefix and suffix passed as the parameters .
Discussions

android - File.createTempFile() vs. new File() - Stack Overflow
Both are working, but in my case the first one is better than the second one because the function createTempFile adds a long random number at the end of the file name making it unique. More on stackoverflow.com
🌐 stackoverflow.com
What is a safe way to create a Temp file in Java? - Stack Overflow
Before Java 7, you might use the legacy methods createTempFile found on the File class. More on stackoverflow.com
🌐 stackoverflow.com
Using createTempFile() method?
>>Will the createTempFile() always create a unique file in the folder chosen, on a single run? Yes. You could just use the timestamp and then add your 1,2,3 etc to it ... >>In the api it does not say this method would add a 5 digit number to end of the filename. The javadoc says, "the name ... More on experts-exchange.com
🌐 experts-exchange.com
May 1, 2006
Need some clarity on usage of createTempFile.
I have gone through many blogs about my question, but I need a quick clarification on the usage of createTempFile. Does this really create a file and… More on reddit.com
🌐 r/javahelp
9
2
November 3, 2024
🌐
Medium
medium.com › @AlexanderObregon › javas-files-createtempfile-method-explained-be6873fc7de0
Java’s Files.createTempFile() Method Explained | Medium
December 27, 2024 - The Files.createTempFile() method provides a simple and effective way to generate temporary files in Java. It is part of the java.nio.file.Files class and is designed to create a new file with a unique name in the default temporary-file directory.
Top answer
1 of 5
48

1. Create file with random name

File file = File.createTempFile(String prefix, String suffix, File parent)
  • Actually create the file on disk and returns the file object
  • Create a file name in this format: prefix + random number + suffix
  • Useful when you need create temporary file on disk

2. Create file with exact name

File file = new File(File parent, String child);
file.createNewFile();
  • Actually create the file on disk and returns true if file get created successfully

  • File name will exactly as pass to child parameter

  • Useful when you need create permanent file on disk

3. Create only file object (in memory)

File file = new File(File parent, String child);
// doesn't create the file on disk until calling createNewFile() method
  • Only create the in memory and not actually on disk
  • Useful when you need just create file object (e.g just to pass it as parameter)

parent parameter can be one of these:

  1. App private directories

    • context.getCacheDir()
    • context.getExternalCacheDir()
    • and ... (full list can be found here)
  2. Public directories

    • Environment.getExternalStorageDirectory()
    • Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES)
    • and ... (full list can be found here)
2 of 5
34

Sounds like your app is creating files, so you need to guarantee unique filenames. You could keep some kind of counter within your app (saved to preferences or DB) and use that. Then you could create shorter/more controlled names, and control uniqueness yourself. Or you can use createTempFile(), which will guarantee you get a unique filename (but you only get partial control of the filename). Sounds like you prefer createTempFile(), so there's no reason not to continue using it if you are happy with the filenames it generates. There's no down side other than not having full control over the filename format.

🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › nio › file › Files.html
Files (Java Platform SE 8 )
April 21, 2026 - public static Path createTempFile(Path dir, String prefix, String suffix, FileAttribute<?>... attrs) throws IOException
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › java.io.file.createtempfile
File.CreateTempFile Method (Java.IO) | Microsoft Learn
Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name. Invoking this method is equivalent to invoking {@link #createTempFile(java.lang.String, java.lang.String, java.io.File) ...
Find elsewhere
Top answer
1 of 3
234

Use File.createTempFile().

File tempFile = File.createTempFile("prefix-", "-suffix");
//File tempFile = File.createTempFile("MyAppName-", ".tmp");
tempFile.deleteOnExit();

Will create a file in the temp dir, like:

prefix-6340763779352094442-suffix

2 of 3
80

NIO.2

Since Java 7 there is the new file API "NIO2" which contains new methods for creating temp files and directories.

Modern Use default temp folder Specify folder
Create folder Files.createTempDirectory Files.createTempDirectory
Create file Files.createTempFile Files.createTempFile

e.g.

Path tempDir = Files.createTempDirectory("tempfiles");

or

Path tempFile = Files.createTempFile("file", ".tmp");

For more info:

  • Oracle’s online tutorial, free-of-cost: File I/O (Featuring NIO.2)
  • Oracle technical notes: NIO and NIO.2 Examples
  • What Is the Difference Between NIO and NIO.2? at Baeldung.com.
  • Introduction to the Java NIO2 File API at Baeldung.com.

Legacy

Before Java 7, you might use the legacy methods createTempFile found on the File class. Notice the name “File” is singular, in contrast to the Files class in modern NIO.2.

Legacy Use default temp folder Specify folder
Create folder
Create file File.createTempFile File.createTempFile

Security note

An important difference between File.createTempFile() (singular File) and Files.createTempFile (plural Files) is also that the latter has more secure permission defaults.

When no file attributes are specified, then the resulting file may have more restrictive access permissions to files created by the File.createTempFile(String,String,File) method.

🌐
Tutorialspoint
tutorialspoint.com › java › io › file_createtempfile_directory.htm
Java - File createTempFile(String prefix, String suffix, File directory) method
The Java File createTempFile(String prefix, String suffix, File directory) method creates a new empty file in the specified directory.
🌐
Kotlin
kotlinlang.org › api › core › kotlin-stdlib › kotlin.io › create-temp-file.html
createTempFile | Core API – Kotlin Programming Language
Use kotlin.io.path.createTempFile instead or resort to java.io.File.createTempFile. Creates a new empty file in the specified directory, using the given prefix and suffix to generate its name.
🌐
Experts Exchange
experts-exchange.com › questions › 21833607 › Using-createTempFile-method.html
Solved: Using createTempFile() method? | Experts Exchange
May 1, 2006 - No, it doesn't actually create the file. You have to open a FileOutputStream or a FileWriter on the File object returned by createTempFile for a file to actually be created.
🌐
Reddit
reddit.com › r/javahelp › need some clarity on usage of createtempfile.
r/javahelp on Reddit: Need some clarity on usage of createTempFile.
November 3, 2024 - https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile(java.lang.String, java.lang.String, java.io.File) [deleted] • 2y ago · Thank you all I’ll look into the sources provided · [deleted] • 2y ago · Comment removed by moderator ·
🌐
Baeldung
baeldung.com › home › java › java io › creating temporary directories in java
Creating Temporary Directories in Java | Baeldung
2 weeks ago - One of the most popular approaches used to create temporary directories is to delegate the destination to the underlying operating system. The location is given by the java.io.tmpdir property, and every operating system has its own structure and cleanup routines.
🌐
Tutorialspoint
tutorialspoint.com › java › io › file_createtempfile.htm
Java - File createTempFile(String prefix, String suffix) method
We're passing both parameters to createTempFile() as tmp and .txt to create the temporary file with prefix as tmp and suffix as .txt. package com.tutorialspoint; import java.io.File; public class FileDemo { public static void main(String[] args) { File f = null; try { // creates temporary file f = File.createTempFile("tmp", ".txt"); // prints absolute path System.out.println("File path: "+f.getAbsolutePath()); } catch(Exception e) { // if any error occurs e.printStackTrace(); } } }
🌐
Mkyong
mkyong.com › home › java › how to get the temporary file path in java
How to get the temporary file path in Java - Mkyong.com
July 17, 2020 - package com.mkyong.io.temp; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; public class TempFilePath2 { public static void main(String[] args) { // Java NIO try { Path temp = Files.createTempFile("", ".tmp"); String absolutePath = temp.toString(); System.out.println("Temp file : " + absolutePath); String separator = FileSystems.getDefault().getSeparator(); String tempFilePath = absolutePath .substring(0, absolutePath.lastIndexOf(separator)); System.out.println("Temp file path : " + tempFilePath); } catch (IOException e) { e.printStackTrace(); } } } Output ·
🌐
Kodejava
kodejava.org › how-do-i-create-a-temporary-file
How do I create temporary file? - Learn Java by Examples
May 23, 2023 - A temporary file can be created by using java.io.File.createTempFile() method. It accepts the prefix, suffix and the path where the file will be stored. When no path is specified it will use the platform default temporary folder.
🌐
CalliCoder
callicoder.com › java-create-temp-file-directory
Java Create Temp File or Directory | CalliCoder
February 18, 2022 - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; public class CreateTempDirectoryExample { public static void main(String[] args) { try { Path tempDirPath = Files.createTempDirectory("tempDir"); System.out.printf("Temporary folder created at %s%n", tempDirPath); } catch (IOException ex) { System.out.format("I/O error: %s%n", ex); } } }
🌐
Codemia
codemia.io › knowledge-hub › path › what_is_a_safe_way_to_create_a_temp_file_in_java
What is a safe way to create a Temp file in Java?
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises
🌐
OpenJDK
bugs.openjdk.org › browse › JDK-4847239
Loading...
(takes time to find this as the ... no longer apparent) ---------- BEGIN SOURCE ---------- import java.io.*; public class Test { public static void main(String[] args) throws IOException { File.createTempFile("Test", ".tmp", new File("c:/xxx")); System.out.println("Created"); ...
🌐
Mkyong
mkyong.com › home › java › how to delete a temporary file in java
How to delete a temporary file in Java - Mkyong.com
July 21, 2020 - In Java, we can use the NIO Files.delete() or Files.deleteIfExists() to delete a temporary file, it works the same like delete a regular text file. // create a temporary file Path path = Files.createTempFile(null, ".log"); // delete Files.delete(path); // or if(Files.deleteIfExists(path)){ // success }else{ // file does not exist } This example uses java.nio to create a temporary file, write a line, and delete it.
🌐
Edureka
edureka.co › blog › how-to-create-a-file-in-java
How to Create a File in Java? Java File Creation with Examples | Edureka
October 1, 2019 - Creating a temporary file using java.io.File.createTempFile() Public class TemporaryFileExample{ Public static void main(string[] args){ try{ final path path = Files.createTempFile("myTempFile",".txt"); System.out.println("Temp file : " + path); ...