Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 899
Adrian Mouat Avatar asked Oct 19 '08 20:10

Adrian Mouat


People also ask

How do I get OutputStream content?

So you can get the OutputStream from that method as : OutputStream os = ClassName. decryptAsStream(inputStream,encryptionKey); And then use the os .

How do I get InputStream from OutputStream?

transferTo() Method. In Java 9 or higher, you can use the InputStream. transferTo() method to copy data from InputStream to OutputStream . This method reads all bytes from this input stream and writes the bytes to the given output stream in the original order.


1 Answers

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 an instance of java.nio.charset.Charset. A possible value is java.nio.charset.StandardCharsets.UTF_8.

The method toString() accepts only a String as a codepage parameter (stand Java 8).

like image 97
Horcrux7 Avatar answered Oct 29 '22 00:10

Horcrux7