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.

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

Comments

Subscribe
Notify of
guest
4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

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.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode