HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / I/O / Java Write to Temporary File

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?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Nageswara Rao

    May 21, 2019

    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.

    • Lokesh Gupta

      May 21, 2019

      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.

  2. Alex

    November 10, 2014

    In the NIO example, where is “file” defined?

    The example can’t be compiled.

    • Lokesh Gupta

      November 11, 2014

      OOPs.. typo. Use path instead. Corrected in program. Thanks for noticing.

Comments are closed on this article!

Search Tutorials

Java IO

  • Java IO Introduction
  • Java How IO works?
  • Java IO vs NIO
  • Java Create File
  • Java Write to File
  • Java Append to File
  • Java Read File
  • Java Read File to String
  • Java Read File to Byte[]
  • Java Make File Read Only
  • Java Copy File
  • Java Copy Directory
  • Java Delete Directory
  • Java Current Working Directory
  • Java Read/Write Properties File
  • Java Read File from Resources
  • Java Read File from Classpath
  • Java Read/Write UTF-8 Data
  • Java Check if File Exist
  • Java Create Temporary File
  • Java Write to Temporary File
  • Java Delete Temporary File
  • Java Read from Console
  • Java Typesafe input using Scanner
  • Java Password Protected Zip
  • Java Unzip with Subdirectories
  • Java Generate SHA/MD5
  • Java Read CSV File
  • Java InputStream to String
  • Java String to InputStream
  • Java OutputStream to InputStream
  • Java InputStreamReader
  • Java BufferedReader
  • Java FileReader
  • Java LineNumberReader
  • Java StringReader
  • Java FileWriter
  • Java BufferedWriter
  • Java FilenameFilter
  • Java FileFilter

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces