Home »
Java Programs »
Java Files & Directories Programs
Create temporary file in specified directory in Java
Creating temporary file in a directory: Here, we are going to learn how to create temporary file in specified directory in Java?
Submitted by IncludeHelp, on July 19, 2019
Problem statement
The task is to create a temporary file in a specified directory.
Creating temporary file in specified directory
To create a temporary file or to create a temporary file in a specified directory we use createTempFile() method. In the first case, we use two parameters (file name and extension), and, in the second case, we use three parameters (file name, extension name and specified directory).
Package to use: import java.io.*;
Syntax
// file object creation with directory name (path)
File tempFile = new File("E://Java");
// creating temporary file in specified directory
File.createTempFile("JavaTemp", ".javatemp", tempFile);
Java program to create temporary file in specified directory
// Java code to create temporary file
// in specified directory
import java.io.*;
public class CreateTempFileinDIR {
public static void main(String[] args) {
// file object to store the result
File result = null;
// file object creation with directory
// name (path)
File tempFile = new File("E://Java");
try {
// creating temporary file in specified directory
result = File.createTempFile("JavaTemp", ".javatemp", tempFile);
} catch (IOException exp) {
System.out.println("Error in creating temporary file : " + exp);
}
// printing the created file path
System.out.println("Temporary file created at : " + tempFile.getPath());
}
}
Output
E:\Programs>javac CreateTempFileinDIR.java
E:\Programs>java CreateTempFileinDIR
Temporary file created at : E:\Java
Java Files & Directories Programs »