Java Temp File

Filed Under: Java

java.io.File 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;

import java.io.File;
import java.io.IOException;

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"));
			System.out.println(tmpFile.getCanonicalPath());
			System.out.println(newFile.getCanonicalPath());
			// write,read data to temporary file like any normal file

			// delete when application terminates
			tmpFile.deleteOnExit();
			newFile.deleteOnExit();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

Output of the above java temp file program is:

java temp file, create temp file in java


/private/var/folders/1t/sx2jbcl534z88byy78_36ykr0000gn/T/data225458400489752329.tmp
/Users/pankaj/temp/text2548249124983543974.temp

That’s all about creating temp file in java.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages