Friday 8 March 2019

Clojure - Java interop: pass an OutputStream argument and get back a String



I'm using a java library and want to call a method which exports data.




This method has two variants: one with a String parameter which is used as a destination file name, and another which accepts an OutputStream object and writes to it with an OutputStreamWriter.



I'd like to use the second method and be able to get back the OutputStream into a String so I can do whatever I want with it.



I'm not sure it is possible actually, but as I found clojure.core/with-out-str I'm having some hope that it is possible, however I'm not sure how to use it.



Is it possible to pass an OutputStream argument to a Java method from Clojure and get back the written data as a String?



Thanks.




Edit:



Actually, the class constructor takes an OutputStream argument, and a method writes through it and closes it.
Hope this helps.


Answer



@xsc's comment pointed to a possible duplicate, still I'll follow his advice on posting an answer myself to keep a reference for Clojure specifics.



Here's what I ended up with:



(def baos (java.io.ByteArrayOutputStream.))


(-> (SomeClass. baos) .export)
(String. (.toByteArray baos) (. java.nio.charset.Charset defaultCharset))


See the comments in this answer for more about Charset.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...