OutputStream is an abstract class provided in the java.io package. Because it is an abstract class, in order to use its functions, we can use its subclasses. Some subclasses are FileOutputStream, ByteArrayOutputStream, ObjectOutputStream, etc. And String is just a sequence of characters, use double quotes to denote it. The java.io.ByteArrayOutputStream.toString() method uses the character set to convert the stream.
Approach 1:
Example:
Input:
String = "Hello World"
Output:
Hello World
Below is the implementation of the above approach:
// Java program to demonstrate conversion // from outputStream to string import java.io.*; class GFG { // we know that main will throw // IOException so we are ducking it public static void main(String[] args) throws IOException { // declaring ByteArrayOutputStream ByteArrayOutputStream stream = new ByteArrayOutputStream(); // Intializing string String st = "Hello Geek!"; // writing the specified byte to the output stream stream.write(st.getBytes()); // converting stream to byte array // and typecasting into string String finalString = new String(stream.toByteArray()); // printing the final string System.out.println(finalString); } }
Output
Hello Geek!
Approach 2:
Example:
Input:
array = [71, 69, 69, 75]
Output:
GEEK
Below is the implementation of the above approach:
// Java program to demonstrate conversion // from outputStream to string import java.io.*; class GFG { public static void main(String[] args) throws IOException { // Intializing empty string // and byte array String str = ""; byte[] bs = { 71, 69, 69, 75, 83, 70, 79, 82, 71, 69, 69, 75, 83 }; // create new ByteArrayOutputStream ByteArrayOutputStream stream = new ByteArrayOutputStream(); // write byte array to the output stream stream.write(bs); // converts buffers using default character set // toString is a method for casting into String type str = stream.toString(); // print System.out.println(str); } }
Output:
GEEKSFORGEEKS
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.