让Clojure识别并隔离文件中的行

ble*_*fly 5 variables io file clojure stream

我试图让Clojure读取一个文件,将第一行放在一个变量中,其余的放在另一个变量中.我似乎无法找到如何做到这一点,如果有人能给我一个头,我会很高兴,

Mic*_*zyk 4

;; 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...
    ...))
Run Code Online (Sandbox Code Playgroud)

更新:啊,刚刚意识到我把问题中的“其余的”意思是“文件中的其余行”,因此上面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)]
  ...)
Run Code Online (Sandbox Code Playgroud)