 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create temporary file in specified directory in Java
A temporary file in the specified directory can be created using the method java.io.File.createTempFile(). This method requires three parameters i.e. the prefix to define the file name, the suffix to define the file extension and the directory in which the temporary file is to be created. It also returns the abstract path name for the temporary file created.
A program that demonstrates this is given as follows −
Example
import java.io.File; public class Demo {      public static void main(String[] args) throws Exception {       File directory = new File("C:/JavaProgram");       File file = File.createTempFile("temp", ".java", directory);       System.out.println(file.getAbsolutePath());       file.deleteOnExit();    } } The output of the above program is as follows −
Output
C:\JavaProgram\temp1333744144499445058.java
Now let us understand the above program.
A temporary file in the specified directory is created using the method java.io.File.createTempFile(). Then the file path is displayed. Also, the method java.io.File.deleteOnExit() is used to delete the temporary file after the program ends. A code snippet that demonstrates this is given as follows −
File directory = new File("C:/JavaProgram"); File file = File.createTempFile("temp", ".java", directory); System.out.println(file.getAbsolutePath()); file.deleteOnExit();