There are a couple issues.
First, your lazy sequence isn't entirely correct. The whole body of the function should by wrapped in lazy-seq
, and it should pass in either the cons to continue the sequence, or nil to terminate it.
(defn byte-chunk-seq [stream]
(lazy-seq (if-let [buf (read-or-nil stream)]
(cons buf (byte-chunk-seq stream))
nil)))
Second, take
is also lazy. So the lazy sequence is not going to be realized until after with-open
has closed the stream. You can avoid this error by wrapping a doall
around the lazy sequence to realize it before the stream is closed.
(with-open [rdr (java.io.FileInputStream. "/tmp/wut")]
(doall (take 2 (byte-chunk-seq rdr))))