Java – writing files in clojure
I am using this function to write files 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 leads to this error:
IllegalArgumentException No matching method found: write for class java.io.BufferedWriter in clojure.lang.Reflector.invokeMatchingMethod (Reflector.java:79)
What did I do wrong here?
Solution
First, your function applies to 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 deliver strange content, we will receive the error you describe:
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 because bufferedwriter has multiple overloaded write versions, and clojure doesn't know which one to call In this case, the conflicting are write (char []) and write (string) For inputs such as string ("a") and integer (1), clojure knows the string version that calls the method, but with other things (for example, clojure set, #{1}), clojure cannot decide
How do you ensure that the input to writelines is indeed strings, or do you use the str function to string them?
Also, look at the spin function