Java Temp File

Filed Under: Java class can be used to create temp file in java. Sometimes we need to create temporary files to be used by our application.

Java Temp File

There are two methods in File class that we can use to create temp file in java.

  1. createTempFile(String prefix, String suffix, File directory): This method creates a temp file with given suffix and prefix in the directory argument.

    The directory should already be existing and should be a directory, else it throws exception.

    The file name is created with random long number, so the file name becomes prefix+random_long_no+suffix.

    This is done to make the application safe as it will be impossible to guess the file name and since application has instance of temp file, we can use it. The prefix String should be minimum three characters long. If suffix is null, “.tmp” suffix is used.

    If directory is null, then temp file is created in operating system temp directory.

  2. createTempFile(String prefix, String suffix): It’s easy way to create temp file in operating system temp directory.

Java Temp File Example

Here is a small java temp file example program.

package com.journaldev.files;


public class JavaTempFile {

	public static void main(String[] args) {
		try {
			File tmpFile = File.createTempFile("data", null);
			File newFile = File.createTempFile("text", ".temp", new File("/Users/pankaj/temp"));
			// write,read data to temporary file like any normal file

			// delete when application terminates
		} catch (IOException e) {


Output of the above java temp file program is:

java temp file, create temp file in java


That’s all about creating temp file in java.

Leave a Reply

Your email address will not be published. Required fields are marked *

Generic selectors
Exact matches only
Search in title
Search in content