Create a temporary file in Java

Java temporary file creation: Here, we are going to learn how to create a temporary file java?
Submitted by IncludeHelp, on July 18, 2019

The task is to create a temporary file in Java.

Creating a temporary file

To create a temporary file in java – we use createTempFile() method of "File" class. The createTempFile() method is called with the File object which should be initialized with the file name (and path if you want to specify).

The createTempFile() method returns a File object, and by using getName() method, we can access the temporary file name.

This method accepts two arguments 1) file_name and 2) file_extension name. If the file_extension is null, the default file extension will be .tmp.

Package to use: import*;


    //file object creation
    File one = null;
    File two = null;

    //temporary file creation
    one = File.createTempFile("file_name", "extension");
    two = File.createTempFile("file_name", "extension");

Java code to create a temporary file

// Java code to create a temporary file  


public class Main {

  public static void main(String[] args) {
    //file object creation to store results
    File one = null;
    File two = null;

    try {
      //creating temporary file1 with extension '.javatemp'
      one = File.createTempFile("sample1", ".javatemp");

      //creating temporary file2 without using null
      two = File.createTempFile("sample2", null);

      System.out.println("file created: " + one.getPath());
      System.out.println("file created: " + two.getPath());

    } catch (IOException exp) {
      System.out.println("Error in creating temporary file: " + exp);


file created: /tmp/sample14223766203657377545.javatemp
file created: /tmp/sample22708977934903691208.tmp

Java Files & Directories Programs »

Comments and Discussions!

Copyright © 2023 All rights reserved.