A Temporary file or a Temp file is a file that is created in order to hold information for some time while a file is being created or modified. After the successful execution of the program or after the program is closed, the temporary file is deleted. Other advantages of having a temporary file are that it helps in storing and moving data, managing settings, help recover lost data, and manage multiple users. Temporary data can be referred to as internet browser cookies, caches that delete after we close the browser or end a session, and deleting them free’s up valuable space on our hard-disk and speed of the computer.
The only reason we need to create a temporary file in java is that we may require it in various situations such as while creating Unit tests, where we don’t want to store the output of the intermediate Java Operations. But if the tests are completed we may delete them as they may unnecessarily occupy space on the computer.
There are two methods that can be used to create temporary files as follows:
- Creating a temporary file on the default location
- Creating a temporary file on the specified location
Method 1: The temporary file is created on the default TEMP folder location.
File.createTempFile(String prefix, String suffix) throws IOException
Method 2: The temporary file is created on the Specified directory.
File.createTempFile(String prefix, String suffix, File directory) throws IOException
Implementation: Both the methods into a Java program later on analyzing the output
As we are now accustomed to the procedure of creating a Temporary file, we will now use it to write data into the Temporary file. The most efficient way to write characters into a temporary file will be by using Java BufferedWriter Class. It is used to provide buffering for writer instances and makes the performance fast.
Implementation: Writing data into a Temporary file
The console output is as follows
The ‘Temp file’ output is as follows:
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.