如何用“〜”代替回家的路径?

时间:2015-04-12 04:25:05

标签: clojure

如果我从命令行传入路径,“〜”会扩展到我的主目录:

(defn -main
  "I don't do a whole lot ... yet."
  [& args]
  (doseq [arg args]
    (println arg)))

britannia:uberjar srseverance$ java -jar args-0.1.0-SNAPSHOT-standalone.jar ~/158.clj 
/Volumes/Macintosh HD/Users/srseverance/158.clj

但是如果我尝试使用包含〜的路径文件,我找不到该文件。

user> (with-open [r (clojure.java.io/reader "~/158.clj")]
        (doall (line-seq r)))
FileNotFoundException ~/158.clj (No such file or directory)  java.io.FileInputStream.open0 (FileInputStream.java:-2)

如何使用“〜/ 158.clj”之类的字符串并获取clojure.java.io/reader可以使用的字符串,例如“/ Volumes / Macintosh HD / Users / srseverance / 158.clj”?

2 个答案:

答案 0 :(得分:5)

您可以定义

(defn expand-home [s]
  (if (.startsWith s "~")
    (clojure.string/replace-first s "~" (System/getProperty "user.home"))
    s))

并使用它来解析主目录:

(clojure.java.io/reader (expand-home "~/158.clj"))]

您还可以查看fs

expand-home库定义

答案 1 :(得分:1)

解决bfontaine的评论,我们可以通过询问系统来获得~user~root的正确结果:

(require '[clojure.java.shell :refer [sh]])

(defn bash [command]
  (sh "bash" "-c" command))

(defn expand [path]
  (-> (str "echo -n " path)
      bash
      :out))

(expand "~")
;; => /home/teodorlu

(expand "~teodorlu")
;; => /home/teodorlu

(expand "~root")
;; => /root

不过,只需将其用于受信任的代码即可!

(expand "`cat ~/.passwords`")
;; => All my passwords!