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:
- At first, we will create an OutputStream.
- We will create a string.
- We will use the write() method to set the string’s value to the OutputStream, we have created before.
- 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
import java.io.*;
public class My_class {
public static void main(String args[]) throws IOException {
ByteArrayOutputStream mystream = new ByteArrayOutputStream();
String mystring = "Welcome To CodeSpeedy";
mystream.write(line.getBytes());
String converted_string = new String(mystream.toByteArray());
System.out.println(converted_string);
}
}Output:
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.
line.getBytes() -> mystring.getBytes()