Temporary Files And Directories in Java

Throughout program execution, we often want to create data that isn’t needed after the program exits. Temporary files and directories are useful for this purpose since they don’t pollute the file system over time.

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class TemporaryFilesAndDirectories {

    private static void check(Exception e) {
        if (e != null) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        try {
            // The easiest way to create a temporary file is by
            // using Files.createTempFile. It creates a file and
            // returns its path. We provide null as the first argument,
            // so it will create the file in the default temporary directory.
            Path tempFile = Files.createTempFile("sample", null);
            System.out.println("Temp file name: " + tempFile);

            // Clean up the file after we're done. The OS is
            // likely to clean up temporary files by itself after
            // some time, but it's good practice to do this
            // explicitly.
            tempFile.toFile().deleteOnExit();

            // We can write some data to the file.
            Files.write(tempFile, new byte[]{1, 2, 3, 4});

            // If we intend to create many temporary files, we may
            // prefer to create a temporary directory.
            // Files.createTempDirectory's arguments are similar to
            // createTempFile's, but it returns a directory path.
            Path tempDir = Files.createTempDirectory("sampledir");
            System.out.println("Temp dir name: " + tempDir);

            tempDir.toFile().deleteOnExit();

            // Now we can create files in this temporary directory.
            Path tempFilePath = tempDir.resolve("file1");
            Files.write(tempFilePath, new byte[]{1, 2});

        } catch (IOException e) {
            check(e);
        }
    }
}

To run the program, compile and execute it using javac and java:

$ javac TemporaryFilesAndDirectories.java
$ java TemporaryFilesAndDirectories
Temp file name: /tmp/sample8390222484788354810.tmp
Temp dir name: /tmp/sampledir4933119451380549492

In this Java version:

  1. We use Files.createTempFile() to create a temporary file, which is similar to os.CreateTemp() in the original code.

  2. Instead of using defer for cleanup, we use deleteOnExit() which ensures the file or directory will be deleted when the JVM exits.

  3. We use Files.createTempDirectory() to create a temporary directory, which is equivalent to os.MkdirTemp().

  4. For writing to files, we use Files.write() method, which is a convenient way to write bytes or strings to a file.

  5. We wrap the main logic in a try-catch block to handle IOExceptions, which is Java’s way of dealing with potential file operation errors.

  6. The check() method is implemented to throw a RuntimeException if an error occurs, similar to the panic() in the original code.

This Java implementation provides the same functionality as the original code, creating and using temporary files and directories in a similar manner.