In this section we will be showing on how to create a temporary file in java. This is necessary when your design is relying in storing values in a temporary file. This source code make use of createTempFile() method of File class under java.io package.
Create temporary file in java
The createTempFile() method takes two arguments, the first one is the prefix and the other is the suffix. This method throws an IOException so we need to catch it or throw it again. The suffix parameter precedes the extension of the generated temp file. The prefix are series of characters that signifies the first characters on the filename of your temporary file followed by a random generated characters that makes the file unique.
package com.javatutorialhq.tutorial; import java.io.File; import java.io.IOException; public class CreateTempFilek{ /** * This java sample code shows how to create a temporary file * Property of javatutorialhq.com * All Rights Reserved * Version 1.0 * 05/18/2012 */ public static void main(String[] args) { try { File ftemp = File.createTempFile("test-temporary-file", ".tmp"); System.out.println(ftemp.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); } } }
Sample Output:
C:\Users\ryan\AppData\Local\Temp\test-temporary-file3274470497038206928.tmp