Java Write to Temporary File

Learn to create a temporary file and write to it in Java. We will use the code sample used for creating temporary file example.

1. BufferedWriter with FileWriter

FileWriter class can be used for writing character files. Wrapping a BufferedWriter around it increases the performance of the program.

Example 1: Java program to create a temporary file and write to it

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class TemporaryFileExample
{
   public static void main(String[] args)
   {
      File temp;
      try
      {
         temp = File.createTempFile("myTempFile", ".txt");

         BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
         bw.write("This is the temporary data written to temp file");

         bw.close();
      } catch (IOException e)
      {
         e.printStackTrace();
      }
   }
}

2. Files.write() – Java NIO

The write() method does the simple thing. It writes bytes to a file. By default, if the temp file does not exist, it will create a new file else overwrites an existing file.

To append to an existing teporary file, use StandardOpenOption.APPEND option while writing the content.

Example 2: Creating a temporary file and writing to it

Due to usage of deleteOnExit(), the file will be deleted when the program exits.

public class TemporaryFileExample
{
   public static void main(String[] args)
   {
      try
      {
         final Path path = Files.createTempFile("myTempFile", ".txt");
         System.out.println("Temp file : " + path);

		 //Writing data here
		 byte[] buf = "some data".getBytes();
		 Files.write(path, buf);

		 //For appending to the existing file
		 //Files.write(path, buf, StandardOpenOption.APPEND);

         //Delete file on exit
         path.toFile().deleteOnExit();

      } catch (IOException e)
      {
         e.printStackTrace();
      }
   }
}

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

4 thoughts on “Java Write to Temporary File”

  1. Hi Gupta,
    Please answer for following question,

    What is the expired time for Temp file, is there any time limit or not, if “Yes” please let me know how much time or shall we set Temp file time ,or if “Not” please let me know what is the exact meaning of Temp File.

    Reply
    • Java docs say – Files.createTempFile() method provides only part of a temporary-file facility. To arrange for a file created by this method to be deleted automatically, use the deleteOnExit() method.

      Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.