Java Program to Convert OutputStream to String

In this Java tutorial, we will learn how to convert OutputStream to string. I hope this Java tutorial will help you to understand the conversion of OutputStream to string in Java. We will use string initializer in this program.

I will explain this conversion through an easy example. Though I will explain the methods I am gonna use in this program and some basic info you need to know. I hope that will make a better sense and understandable for all the readers.

Here we will use these following:

  • ByteArrayOutputStream Class
  • String Class
  • write() method
  • toByteArray() method

Guess The Number Game Using Java with Source Code

How to Convert OutputStream to String in Java with Example

We will follow the following steps:

  1. At first, we will create an OutputStream.
  2. We will create a string.
  3. We will use the write() method to set the string’s value to the OutputStream, we have created before.
  4. Finally, we will create another string. Then we will use the toByteArray() method to convert the OutputStream value into a string. We will store this string value in our lastly created final string.

How to convert image to byte array in Java

Here is a simple example to Convert OutputStream to String in Java

public class My_class {
    public static void main(String args[]) throws IOException {
        ByteArrayOutputStream mystream = new ByteArrayOutputStream();
        String mystring = "Welcome To CodeSpeedy";
        String converted_string = new String(mystream.toByteArray());


Welcome To CodeSpeedy

how to convert Object array to String array in java

In the above program, we have used ByteArrayOutputStream class to create an OutputStream. Then we have stored a string in it with the help of write() method. Then finally, mystream.toByteArray() method to reach our goal.

One response to “Java Program to Convert OutputStream to String”

  1. Stan says:

    line.getBytes() -> mystring.getBytes()

Leave a Reply

Your email address will not be published. Required fields are marked *