The temporary file is just a regular file created on a predefined directory. In Java, we can use the NIO Files.write() to write data to a temporary file.

  // create a temporary file
  Path tempFile = Files.createTempFile(null, null);

  // Writes a string to the above temporary file
  Files.write(tempFile, "Hello World\n".getBytes(StandardCharsets.UTF_8));

  // Append
  List<String> content = Arrays.asList("Line 1", "Line 2", "Line 3");
  Files.write(tempFile, content, StandardOpenOption.APPEND);

1. Write to Temporary File – Java NIO

In Java, there are many ways to write data or text to a temporary file; it works like writing to a regular file. You can choose BufferedWriterFileWriter etc, but in most cases, the NIO java.nio.Files should be enough to write or append data to a file.

1.2 This example uses java.nio.Files to create a temporary file, write a line, append a list of lines, and read the temporary file and print put its content.

TempFileWrite1.java

package com.favtuts.io.temp;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class TempFileWrite {

    public static void main(String[] args) {
        
        try {

            // create a temporary file
            Path tempFile = Files.createTempFile(null, null);
            System.out.println(tempFile);

            // write a line
            Files.write(tempFile, "Hello World\n".getBytes(StandardCharsets.UTF_8));

            // append a list of lines, add new lines automatically
            List<String> content = Arrays.asList("Line 1", "Line 2", "Line 3");
            Files.write(tempFile, content, StandardOpenOption.APPEND);

            // read a temp file, Java 11
            //String tempFileContent = Files.readString(tempFile);
            //System.out.println(tempFileContent);

            // Java 8
            String tempFileContent = Files
                    .lines(tempFile, StandardCharsets.UTF_8)
                    .collect(Collectors.joining(System.lineSeparator()));
            System.out.println(tempFileContent);

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

Output

/tmp/545377489462547049.tmp
Hello World
Line 1
Line 2
Line 3

1.2 This example uses NIO Files to create a temporary file and BufferedWriter to write a line to the temporary file.

  Path tempFile = Files.createTempFile(null, null);

  try (BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile.toFile()))) {
      bw.write("This is the temporary file content");
  }

2. Write to Temporary File – Java Legacy IO

This example uses the legacy IO java.io to create a temporary file, BufferedWriter to write three lines to the temporary file, and read the temporary file using BufferedReader.

TempFileWrite2.java

package com.favtuts.io.temp;

import java.io.*;
import java.util.Arrays;
import java.util.List;

public class TempFileWrite2 {

    public static void main(String[] args) {

        try {

            File file = File.createTempFile("abc", ".tmp");
            System.out.println(file);

            // writes few lines
            List<String> content = Arrays.asList("Line 1", "Line 2", "Line 3");
            try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
                for (String s : content) {
                    bw.write(s);
                    bw.write(System.lineSeparator()); // new line
                }
            }

            // read from a temporary file
            try (BufferedReader br = new BufferedReader(new FileReader(file))) {
                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }
            }

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

    }

}

Output

/tmp/abc6568347546046588668.tmp
Line 1
Line 2
Line 3

Download Source Code

$ git clone https://github.com/favtuts/java-core-tutorials-examples

$ cd java-io/temp

References

Leave a Reply

Your email address will not be published. Required fields are marked *