概述

一次讀取所有檔案(不推薦用於大檔案):

(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