Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Java 8 create temporary file


How to create a temporary file in Java 8?

Sometimes it’s needed to create a temporary file during tests, verify result, and then delete it at the end. As usual it can be easily done using Java 8 Files API.


package com.farenda.solved;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class JavaSolved {

    public static void main(String[] args) throws IOException {
        String filename = createTempFile();

    // Creates a temporary file that will be deleted on JVM exit.
    private static String createTempFile() throws IOException {
        // Since Java 1.7 Files and Path API simplify operations on files
        Path path = Files.createTempFile("sample-file", ".txt");
        File file = path.toFile();
        // writing sample data
        Files.write(path, "Temporary content...".getBytes(StandardCharsets.UTF_8));
        // This tells JVM to delete the file on JVM exit.
        // Useful for temporary files in tests.
        return file.getAbsolutePath();

    private static void printContent(String filename) throws IOException {
        System.out.println("Reading from: " + filename);
        // In Java 8 you can use forEach() method instead of iterating collection.
        // Moreover static methods can be passed as an arguments.


Running the program gives the following output:

Reading from: /tmp/sample-file9131501422971123075.txt
Temporary content...

As you can see the file has specified prefix sample-file and designated suffix .txt. Now, when you list files in /tmp directory (or %TEMP% in Windows) you can verify that the file has been deleted:

$> ls -l /tmp/sample*
ls: cannot access /tmp/sample*: No such file or directory
Share with the World!