Frage

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.

War es hilfreich?

Lösung

@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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top