我想让Clojure读取一个文件,将第一行放入一个变量中,将其余部分放入另一个变量中。
我似乎无法找到如何实现这一点的方法,如果有人能够帮我解决问题,我将不胜感激。
;; for Clojure 1.1
(require '[clojure.contrib.duck-streams :as io])
;; for bleeding edge
(require '[clojure.java.io :as io])
(with-open [fr (io/reader "/path/to/the/file")]
(let [[first-line & other-lines] (doall (line-seq fr))]
;; do stuff with the lines below...
...))
更新: 啊,刚才意识到我从问题中取出的“其余部分”是指“文件中的其余行”,因此在上面的代码中other-lines
是除第一行外文件中所有行的序列。
如果你需要“包含文件其余内容的字符串”,则可以使用上面的代码,但是需要使用 (require '[clojure.contrib.str-utils2 :as str])
/ (require '[clojure.string :as str])
(取决于你使用的Clojure版本),然后说(str/join "\n" other-lines)
将other-lines
重新连接成一个字符串; 或者,您也可以使用类似以下的东西:
(let [contents (slurp "/path/to/the/file")
[first-line rest-of-file] (.split #"\n" contents 2)]
...)
(require '[clojure.string :as str])
(let [[f & r] (str/split (slurp "foo.txt") #"\n")]
... do something with f and r ...)
ED: 不知何故,我没有认出Michał的答案,曾考虑删除它,但由于它略有不同并展示了clojure.string.split,我决定保留。