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

Syntax:

    //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  

import java.io.*;

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);
    }
  }
}

Output

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

Java Files & Directories Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.