
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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 a Temporary File in Java
A temporary file can be created using the method java.io.File.createTempFile(). This method requires two parameters i.e. the prefix to define the file name and the suffix to define the file extension. 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 file = File.createTempFile("temp", null); System.out.println(file.getAbsolutePath()); file.deleteOnExit(); } }
The output of the above program is as follows −
Output
C:\Users\amit_\AppData\Local\Temp\temp6072597842246154962.tmp
Now let us understand the above program.
A temporary file 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 file = File.createTempFile("temp", null); System.out.println(file.getAbsolutePath()); file.deleteOnExit();
Advertisements