gpt4 book ai didi

clojure - 如何用 "~"替换主页路径?

转载 作者:行者123 更新时间:2023-12-02 10:54:44 25 4
gpt4 key购买 nike

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

(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”?

最佳答案

您可以定义

(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 的库定义,它解决了下面 bfontaine 评论中概述的 ~foo 问题:

(let [homedir (io/file (System/getProperty "user.home"))
usersdir (.getParent homedir)]
(defn home
"With no arguments, returns the current value of the `user.home` system
property. If a `user` is passed, returns that user's home directory. It
is naively assumed to be a directory with the same name as the `user`
located relative to the parent of the current value of `user.home`."
([] homedir)
([user] (if (empty? user) homedir (io/file usersdir user)))))

(defn expand-home
"If `path` begins with a tilde (`~`), expand the tilde to the value
of the `user.home` system property. If the `path` begins with a
tilde immediately followed by some characters, they are assumed to
be a username. This is expanded to the path to that user's home
directory. This is (naively) assumed to be a directory with the same
name as the user relative to the parent of the current value of
`user.home`."
[path]
(let [path (str path)]
(if (.startsWith path "~")
(let [sep (.indexOf path File/separator)]
(if (neg? sep)
(home (subs path 1))
(io/file (home (subs path 1 sep)) (subs path (inc sep)))))
path)))

关于clojure - 如何用 "~"替换主页路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29585928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com