0

In Conjure, I need to read in a long file, too long to slurp in, and I wish to pass the open file pointer into method, which I can call recursively, reading until it is empty. I have found examples using open-with, but is there a way to open a file and then read from it inside of a function? Points to examples or docs would be helpful.

2 Answers 2

2

Is this along the lines of what you have in mind?

(defn process-file [f reader]
  (loop [lines (line-seq reader) acc []]
    (if (empty? lines)
      acc
      (recur (rest lines) (conj acc (f (first lines)))))))

(let [filename "/path/to/input-file"
      reader (java.io.BufferedReader. (java.io.FileReader. filename))]
  (process-file pr-str reader))

Note that if you (require '[clojure.java.io :as io]) you can use io/reader as a shortcut for invoking BufferedReader and FileReader directly. However, using with-open would still be preferable - it will ensure the file is closed properly, even in the event of an exception - and you can absolutely pass the open reader to other functions from within a with-open block.

Here's how you could make use of with-open in the scenario you use in the answer you've posted, passing the reader and writer objects to a function:

(with-open [rdr (io/reader "/path/to/input-file")]
  (with-open [wtr (io/writer "/path/to/output-file")]
    (transfer rdr wtr)))

I should also note that in my example scenario it would be preferable to map or reduce over the line-seq but I used loop/recur since you asked about recursion.

Here's the ClojureDocs page on the clojure.java.io namespace.

Sign up to request clarification or add additional context in comments.

Comments

0

Playing around I discovered the answer, so for any others looking, here is a version of my solution.

(defn transfer
  [inFile outFile]
  (.write outFile (.read inFile))
...

...
(transfer (clojure.java.io/reader "fileIn.txt)
          (clojure.java.io/writer "out.txt"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.