Temporary Files and Directories in Clojure

Our program demonstrates how to work with temporary files and directories in Clojure. Here’s the full source code:

(ns temporary-files-and-directories
  (:require [clojure.java.io :as io])
  (:import (java.nio.file Files)
           (java.nio.file.attribute FileAttribute)))

(defn check [e]
  (when e
    (throw (Exception. e))))

(defn -main []
  (let [temp-file (Files/createTempFile "sample" ".tmp" (into-array FileAttribute []))]
    (println "Temp file name:" (.toString temp-file))
    
    ; Clean up the file after we're done
    (.deleteOnExit temp-file)
    
    ; We can write some data to the file
    (with-open [writer (io/writer temp-file)]
      (.write writer (byte-array [1 2 3 4])))
    
    ; Create a temporary directory
    (let [temp-dir (Files/createTempDirectory "sampledir" (into-array FileAttribute []))]
      (println "Temp dir name:" (.toString temp-dir))
      
      ; Clean up the directory after we're done
      (.deleteOnExit (.toFile temp-dir))
      
      ; Now we can synthesize temporary file names by prefixing them with our temporary directory
      (let [file-path (.resolve temp-dir "file1")]
        (Files/write file-path (byte-array [1 2]) (into-array java.nio.file.OpenOption []))))))

(-main)

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.

The easiest way to create a temporary file in Clojure is by using Files/createTempFile. It creates a file and returns a Path object. We provide "sample" as the prefix and ".tmp" as the suffix for the file name.

We display the name of the temporary file. On Unix-based OSes the directory will likely be /tmp. The file name starts with the prefix given as the first argument to Files/createTempFile and the rest is chosen automatically to ensure that concurrent calls will always create different file names.

We use .deleteOnExit to ensure the file is deleted when the JVM exits. It’s good practice to clean up temporary files explicitly.

We can write some data to the file using a writer.

If we intend to write many temporary files, we may prefer to create a temporary directory. Files/createTempDirectory works similarly to createTempFile, but it returns a directory Path rather than a file Path.

We can synthesize temporary file names by resolving them against our temporary directory Path.

When you run this program, you’ll see output similar to:

Temp file name: /tmp/sample3521528116476566727.tmp
Temp dir name: /tmp/sampledir4733215473590439953

Remember that the actual file and directory names will be different each time you run the program.