概述

一次读取所有文件(不推荐用于大文件):

(slurp "./small_file.txt")

一次将数据写入文件:

(spit "./file.txt" "Ocelots are Awesome!")    ; overwrite existing content
(spit "./log.txt" "2016-07-26 New entry." :append true)

逐行读取文件:

(use 'clojure.java.io)
(with-open [rdr (reader "./file.txt")]
    (line-seq rdr)    ; returns lazy-seq
)    ; with-open macro calls (.close rdr)

逐行写文件:

(use 'clojure.java.io)
(with-open [wrtr (writer "./log.txt" :append true)]
    (.write wrtr "2016-07-26 New entry.")
)    ; with-open macro calls (.close wrtr)

写入文件,替换现有内容:

(use 'clojure.java.io)
(with-open [wrtr (writer "./file.txt")]
    (.write wrtr "Everything in file.txt has been replaced with this text.")
)    ; with-open macro calls (.close wrtr)

笔记:

  • 你可以指定 URL 和文件
  • (slurp)(spit) 的选项分别传递给 clojure.java.io/reader/writer