- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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();
- Related Articles
- Create temporary file with specified extension suffix in Java
- Create a temporary file in Java
- Java Program to get name of specified file or directory
- Get Operating System temporary directory / folder in Java
- How to create a new directory by using File object in Java?
- Rename file or directory in Java
- How to delete a temporary file in Java?
- Golang program to create a temporary file
- Create a directory in Java
- Delete the file or directory in Java
- Check for file or directory in Java
- How to create a temporary file using PowerShell?
- Determine if file or directory exists in Java
- Delete file or directory on termination in Java
- Mark file or directory Read Only in Java
