I write this function, but what's its return value.
(defn read-data [file]
(let [code (subs (.getName file) 0 3)]
(with-open [rdr (clojure.java.io/reader file)]
(drop 1 (line-seq rdr)))))
(def d (read-data "data.db"))
It's OK til now. But when I want print this out.
(clojure.pprint/pprint d)
I got a exception:
Exception in thread "main" java.lang.RuntimeException: java.io.IOException: Stream closed
so I confused, what's wrong? The return value isn't a list? How to debug in this situation as an newbie?
Thanks!
The problem is that line-seq
is lazy and that the reader is closed by the time it is evaluated.
That means all the lines need to be read within the scope of your with-open
. One option is to force the full evaluation of line-seq
by using doall
, as shown below.
(drop 1 (doall (line-seq rdr)))
A potential problem with this approach is that you'll get an OutOfMemoryError if the file is larger than the available memory. So, depending on what you are trying to accomplish, there might be other less memory-intensive solutions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With