Processing a file character by character in Clojure

后端 未结 3 1995
礼貌的吻别
礼貌的吻别 2020-12-20 21:38

I\'m working on writing a function in Clojure that will process a file character by character. I know that Java\'s BufferedReader class has the read() method that reads one

3条回答
  •  萌比男神i
    2020-12-20 22:04

    (with-open [reader (clojure.java.io/reader "path/to/file")] ...
    

    I prefer this way to get a reader in clojure. And, by character by character, do you mean in file access level, like read, which allow you control how many bytes to read?

    Edit

    As @deterb pointed out, let's check the source code of line-seq

    (defn line-seq
      "Returns the lines of text from rdr as a lazy sequence of strings.
       rdr must implement java.io.BufferedReader."
      {:added "1.0"
       :static true}
      [^java.io.BufferedReader rdr]
      (when-let [line (.readLine rdr)]
        (cons line (lazy-seq (line-seq rdr)))))
    

    I faked a char-seq

     (defn char-seq 
       [^java.io.Reader rdr]
       (let [chr (.read rdr)]
         (if (>= chr 0)
         (cons chr (lazy-seq (char-seq rdr))))))
    

    I know this char-seq reads all chars into memory[1], but I think it shows that you can directly call .read on BufferedReader. So, you can write your code like this:

    (let [chr (.read rdr)]
      (if (>= chr 0)
        ;do your work here
      ))
    

    How do you think?

    [1] According to @dimagog's comment, char-seq not read all char into memory thanks to lazy-seq

提交回复
热议问题