3

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.

Arnaud
  • 1,121
  • 1
  • 11
  • 26
  • If you pass a `ByteArrayOutputStream` to your method you should be able to retrieve the written data. See this answer: http://stackoverflow.com/a/216913/1916789. – xsc May 14 '14 at 08:26
  • Worked like a charm. Could you please create an answer from your comment so I can accept it? Thanks. – Arnaud May 14 '14 at 08:37
  • Not sure I should since this is basically a duplicate question and my answer would not consist of anything worthwhile. I suggest you write the answer yourself, maybe including the piece of Clojure code that solved your problem. This might be more helpful. :) – xsc May 14 '14 at 08:51

1 Answers1

5

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

Community
  • 1
  • 1
Arnaud
  • 1,121
  • 1
  • 11
  • 26