---
title: "Get an OutputStream into a String"  
description: "Get an OutputStream into a String"  
author: "Anonymous User"  
published: 2015-08-10  
updated: 2015-08-11  
canonical: https://www.mindstick.com/forum/33408/get-an-outputstream-into-a-string  
category: "java"  
tags: ["java", "string"]  
reading_time: 1 minute  

---

# Get an OutputStream into a String

What's the best way to pipe the [output](https://www.mindstick.com/interview/34427/explain-the-output-in-angular) from an [java](https://www.mindstick.com/articles/12214/web-development-company-in-india-laid-on-the-foundation-of-concrete-java-programming).io.OutputStream to a [String](https://www.mindstick.com/articles/1527/string-split-in-c-sharp) in Java?\
[Say](https://answers.mindstick.com/qa/116645/a1-wreckers-reviews-what-do-customers-say) I have the [method](https://www.mindstick.com/forum/166/webservice-method):\

```
  writeToStream(Object o, OutputStream out)
```

Which writes certain [data](https://www.mindstick.com/articles/13050/salesforce-aiming-to-dominate-predictive-analytics-with-data-science) 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](https://www.mindstick.com/articles/12997/5-essential-tips-on-resume-writing-for-business-analysts) a [class](https://www.mindstick.com/blog/165/generic-class-in-c-sharp) 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](https://yourviews.mindstick.com/story/1427/explosive-facts-about-trinity-test-world-s-first-nuclear-bomb)!

## Replies

### Reply by Anonymous User

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 accept only a String as codepage parameter (stand Java 8).


---

Original Source: https://www.mindstick.com/forum/33408/get-an-outputstream-into-a-string

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
