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.
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 becomesprefix+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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
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:
1 2 3 4 |
/private/var/folders/1t/sx2jbcl534z88byy78_36ykr0000gn/T/data225458400489752329.tmp /Users/pankaj/temp/text2548249124983543974.temp |
That’s all about creating temp file in java.