Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Java by (3.4k points)

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 Answer

0 votes
by (46k points)

I would use a ByteArrayOutputStream. And on finish you can call:

new String( baos.toByteArray(), codepage );

or better baos.toString( codepage );

For the String constructor, the codepage can be a String or a syntax of java.nio.charset.Charset. A potential value is java.nio.charset.StandardCharsets.UTF_8.

The method toString takes only a String as code page parameter (stand Java 8).

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...