Writing to Temporary File in Java

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

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

1. Writing Char Data using BufferedWriter with FileWriter

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

FileWriter fw = null;
BufferedWriter bw = null;
try {
  File tempFile = File.createTempFile("data", ".txt");
  
  fw = new FileWriter(tempFile);
  bw = new BufferedWriter(fw);
  bw.write("This is the temporary data written to temp file");
} catch (IOException e) {
  e.printStackTrace();
}
finally {
  fw.close();
  bw.close();
}

2. Writing Bytes using Files.write()

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 temporary file, use StandardOpenOption.APPEND option while writing the content.
  • Due to usage of deleteOnExit(), the file will be deleted when the program exits.
try {
  final Path path = Files.createTempFile("myTempFile", ".txt");

  // 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 !!

Source Code on Github

Leave a Comment

  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

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.