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:
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:
Remember that the actual file and directory names will be different each time you run the program.