In Clojure 1.3, How to read and write a file

后端 未结 6 504
夕颜
夕颜 2020-12-07 06:48

I\'d like to know the \"recommended\" way of reading and writing a file in clojure 1.3 .

  1. How to read the whole file
  2. How to read a file line by line
6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-07 07:15

    If the file fits into memory you can read and write it with slurp and spit:

    (def s (slurp "filename.txt"))
    

    (s now contains the content of a file as a string)

    (spit "newfile.txt" s)
    

    This creates newfile.txt if it doesnt exit and writes the file content. If you want to append to the file you can do

    (spit "filename.txt" s :append true)
    

    To read or write a file linewise you would use Java's reader and writer. They are wrapped in the namespace clojure.java.io:

    (ns file.test
      (:require [clojure.java.io :as io]))
    
    (let [wrtr (io/writer "test.txt")]
      (.write wrtr "hello, world!\n")
      (.close wrtr))
    
    (let [wrtr (io/writer "test.txt" :append true)]
      (.write wrtr "hello again!")
      (.close wrtr))
    
    (let [rdr (io/reader "test.txt")]
      (println (.readLine rdr))
      (println (.readLine rdr)))
    ; "hello, world!"
    ; "hello again!"
    

    Note that the difference between slurp/spit and the reader/writer examples is that the file remains open (in the let statements) in the latter and the reading and writing is buffered, thus more efficient when repeatedly reading from / writing to a file.

    Here is more information: slurp spit clojure.java.io Java's BufferedReader Java's Writer

提交回复
热议问题