Create Temporary File in Java

 Posted On  | Yashwant Chavan 

In this tutorial we will learn how to create temporary file in Java. There are two static methods createTempFile() in the Java File class, Which will help to create temp file on default TEMP folder location and another one is used to create temp file on specified folder location.

File.createTempFile() method syntax

public static File createTempFile(String prefix,String suffix,File directory) throws IOException

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 createTempFile(prefix, suffix, null).

The Files.createTempFile() method provides an alternative method to create an empty file in the temporary-file directory. Files created by that method may have more restrictive access permissions to files created by this method and so may be more suited to security-sensitive applications.

Parameters prefix The prefix string to be used in generating the file's name; must be at least three characters long suffix. The suffix string to be used in generating the file's name; may be null, in which case the suffix ".tmp" will be used.

Returns - An abstract pathname denoting a newly-created empty file.

Throws - IllegalArgumentException - If the prefix argument contains fewer than three characters. IOException - If a file could not be created. SecurityException - If a security manager exists and its java.lang.SecurityManager.checkWrite(java.lang.String) method does not allow a file to be created

Create Temp File Example

In below example we have created two temp files. In first method call temp file is created on window's default TEMP folder location. In second method call we have specified the directory in which the file is to be created.



public class TempFileExample {

    public static void main(String[] args) {
        try {

            File tempFile = File.createTempFile("hello", ".tmp");
            System.out.println("Temp file On Default Location: " + tempFile.getAbsolutePath());
            tempFile = File.createTempFile("hello", ".tmp", new File("C:/"));
            System.out.println("Temp file On Specified Location: " + tempFile.getAbsolutePath());

        } catch (IOException e) {



Temp file On Default Location: C:\Users\swami\AppData\Local\Temp\hello7828748332363277400.tmp
Temp file On Specified Location: C:\hello950036450024130433.tmp

© 2018

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0356 seconds.