Asked • 04/10/19

Get an OutputStream into a String?

What's the best way to pipe the output from an java.io.OutputStream to a String in Java? Say I have the method: writeToStream(Object o, OutputStream out) Which writes certain data from the object to the given stream. However, I want to get this output into a String as easily as possible. I'm considering writing a class like this (untested): class StringOutputStream extends OutputStream { StringBuilder mBuf; public void write(int byte) throws IOException { mBuf.append((char) byte); } public String getString() { return mBuf.toString(); } } But is there a better way? I only want to run a test!

1 Expert Answer

By:

Milad G. answered • 03/11/20

Tutor
5 (13)

Software Engineer + Computer Science Degree | Crypto/Meta Consultant

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.