Writing to a file in Clojure

I use this function to write to a file in Clojure.

(defn writelines [file-path lines] (with-open [wtr (clojure.java.io/writer file-path)] (doseq [line lines] (.write wtr line)))) 

But this always raises this error:

 IllegalArgumentException No matching method found: write for class java.io.BufferedWriter in clojure.lang.Reflector.invokeMatchingMethod (Reflector.java:79) 

What am I doing wrong here?

+6
source share
3 answers

First of all, your function works great for many inputs:

 Clojure 1.3.0 user=> (defn writelines [file-path lines] (with-open [wtr (clojure.java.io/writer file-path)] (doseq [line lines] (.write wtr line)))) #'user/writelines user=> (writelines "foobar" ["a" "b"]) nil user=> (writelines "quux" [1 2]) nil 

However, when you try to convey something strange, we get the error you described:

 user=> (writelines "quux" [#{1}]) IllegalArgumentException No matching method found: write for class java.io.BufferedWriter clojure.lang.Reflector.invokeMatchingMethod (Reflector.java:79) 

This error is due to the fact that BufferedWriter has several overloaded versions of write and clojure does not know which one to call. In this case, write(char[]) and write(String) are conflicting. With inputs like strings ( "a" ) and clojure integers ( 1 ), it was known that he was calling the version of the String method, but with something else (like clojure set, #{1} ) clojure couldn't solve .

How to guarantee that the writelines inputs writelines really String or their string use with the str function?

Also see the spit function .

+17
source

Try the following:

 (defn writelines [file-path lines] (with-open [wtr (clojure.java.io/writer file-path)] (binding [*out* wtr] (doseq [line lines] (print wtr line))))) 

If you look at the documentation for BufferedWriter , you won’t see the corresponding method how you called write (screams, I missed the inherited methods, silly!). It seems to me that binding to *out* easiest thing around (if you also do not want to output debugging information, in which case it can be a little more complicated).

+1
source

When following a message, line exceptions are not seq lines, ints (chars) or int array.

0
source

Source: https://habr.com/ru/post/904058/


All Articles