- 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
Temporary files in Java
In certain scenarios such as unit testing, or for some application logics you might need to create temporary files.
Creating a temporary file
The File class in Java provides a method with name createTempFile(). This method accepts two String variables representing the prefix (starting name) and suffix(extension) of the temp file and a File object representing the directory (abstract path) at which you need to create the file.
Example
Following Java example creates a temporary file named exampleTempFile5387153267019244721.txt in the path D:/SampleDirectory
import java.io.File; import java.io.IOException; public class TempararyFiles { public static void main(String args[]) throws IOException { String prefix = "exampleTempFile"; String suffix = ".txt"; //Creating a File object for directory File directoryPath = new File("D:/SampleDirectory"); //Creating a temp file File.createTempFile(prefix, suffix, directoryPath); System.out.println("Temp file created........."); } }
Output
Temp file created.........
Deleting a temporary file
The File class provides a delete() method which deletes the current file or directory, invoke this method on the temporary file.
Example
The following Java program creates and deletes a temp file.
import java.io.File; import java.io.IOException; public class TempararyFiles { public static void main(String args[]) throws IOException { String prefix = "exampleTempFile"; String suffix = ".txt"; //Creating a File object for directory File directoryPath = new File("D:/SampleDirectory"); //Creating a temp file File tempFile = File.createTempFile(prefix, suffix, directoryPath); System.out.println("Temp file created: "+tempFile.getAbsolutePath()); //Deleting the file tempFile.delete(); System.out.println("Temp file deleted........."); } }
Output
Temp file created: D:\SampleDirectory\exampleTempFile7179732984227266899.txt Temp file deleted.........
Advertisements
To Continue Learning Please Login
Login with Google