Q:

Create a temporary file in Java

belongs to collection: Java Files & Directories Programs

0

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

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Create temporary file in specified directory in Ja... >>
<< Create a new empty file in Java...