Skip to content

Instantly share code, notes, and snippets.

@lnostdal
Last active August 27, 2021 10:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lnostdal/cc956e2a80dc49d8097b7c950f7213bd to your computer and use it in GitHub Desktop.
Save lnostdal/cc956e2a80dc49d8097b7c950f7213bd to your computer and use it in GitHub Desktop.
Move a file atomically in Clojure
;;; Move a file atomically in Clojure.
;; This will also replace the target file if it exists since REPLACE_EXISTING is included in the options at the end.
;; user.dir == current working directory (on Linux at least).
(let [source-filename (str (System/getProperty "user.dir") "/source.txt")
target-filename (str (System/getProperty "user.dir") "/target.txt")
source-file (java.nio.file.Paths/get (java.net.URI/create (str "file://" source-filename)))
target-file (java.nio.file.Paths/get (java.net.URI/create (str "file://" target-filename)))]
(java.nio.file.Files/move source-file target-file
(into-array java.nio.file.CopyOption
[(java.nio.file.StandardCopyOption/ATOMIC_MOVE)
(java.nio.file.StandardCopyOption/REPLACE_EXISTING)])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment