Java Program to Convert OutputStream to String
OutputStream is an abstract class that is available in the java.io package. As it is an abstract class in order to use its functionality we can use its subclasses. Some subclasses are FileOutputStream, ByteArrayOutputStream, ObjectOutputStream etc. And a String is nothing but a sequence of characters, use double quotes to represent it. The java.io.ByteArrayOutputStream.toString() method converts the stream using the character set.
Approach 1:
- Create an object of ByteArrayoutputStream.
- Create a String variable and initialize it.
- Use the write method to copy the contents of the string to the object of ByteArrayoutputStream.
- Print it.
Example:
Input : String = "Hello World"
Output: Hello World
Below is the implementation of the above approach:
Java
import java.io.*;
class GFG {
public static void main(String[] args)
throws IOException
{
ByteArrayOutputStream stream
= new ByteArrayOutputStream();
String st = "Hello Geek!" ;
stream.write(st.getBytes());
String finalString
= new String(stream.toByteArray());
System.out.println(finalString);
}
}
|
Approach 2:
- Create a byte array and store ASCII value of the characters.
- Create an object of ByteArrayoutputStream.
- Use write method to copy the content from the byte array to the object.
- Print it.
Example:
Input : array = [71, 69, 69, 75]
Output: GEEK
Below is the implementation of the above approach:
Java
import java.io.*;
class GFG {
public static void main(String[] args)
throws IOException
{
String str = "" ;
byte [] bs = { 71 , 69 , 69 , 75 , 83 , 70 , 79 ,
82 , 71 , 69 , 69 , 75 , 83 };
ByteArrayOutputStream stream
= new ByteArrayOutputStream();
stream.write(bs);
str = stream.toString();
System.out.println(str);
}
}
|
Last Updated :
09 Dec, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...