ADVERTISEMENT
ADVERTISEMENT

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 »


ADVERTISEMENT




ADVERTISEMENT


Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.