How to Convert a String into the InputStream in Java Program
Java Strings
- In Java, a string is a sequence of characters. It is an object of the class java.lang.String, which is defined in the Java standard library.
- Java provides many useful methods for working with strings, such as finding the length of a string, converting strings to upper or lower case, and searching for substrings within a string.
- You must be familiar with following topics to understand the correspond example Such as: Java Strings,
Java InputStream Class, Java ByteArrayInputStream Class. - To understand the how to Convert a String into the InputStream in java Program, Read the Full Aerticle
Steps to Convert a String into the InputStream in Java Program
- Here are the Steps to Convert a String into the InputStream in Java Program:, You can follow these steps:
- There are several ways to convert a string into an input stream in Java, but here are the steps for the most common approach using the ByteArrayInputStream class:
- Convert the string into a byte array: Use the getBytes() method of the String class to convert the string into a byte array, for example: byte[] bytes = str.getBytes();
- Create a ByteArrayInputStream object: Pass the byte array created in step 1 as a parameter to the constructor of the ByteArrayInputStream class, for example: ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
- Read the data from the input stream: Use the methods of the InputStream class, such as read(), read(byte[] b), or read(byte[] b, int off, int len), to read the data from the input stream.
- Close the input stream: After you have finished reading the data from the input stream, use the close() method of the InputStream class to close the stream and release any associated resources.
Java InputStream Class:
The InputStream class is a fundamental class in the Java I/O library, and it is the parent class of all classes representing an input stream of bytes.
An InputStream is an abstract representation of a stream of bytes that can be read from a source, such as a file, network socket, or in-memory buffer.
Java ByteArrayInputStream Class:
The ByteArrayInputStream class is a subclass of the InputStream class in Java, and it is used to read data from a byte array.The byte array can be created either from a string or from an existing array of bytes.
The ByteArrayInputStream class is a convenient way to read data from a byte array, and it is often used in conjunction with the ByteArrayOutputStream class to write data to a byte array and then read it back as an input stream.
Let’s look at a Java Program to Convert a String into the InputStream to perform certain operations.
Example 1: Java Program to Convert a String into the InputStream.
Run
import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.IOException; public class Main { public static void main(String[] args) { String string = "Hey, prepsters!"; InputStream inputStream = new ByteArrayInputStream(string.getBytes()); try { int data = inputStream.read(); while (data != -1) { System.out.print((char) data); data = inputStream.read(); } } catch (IOException e) { System.err.println("An I/O error occurred while reading the input stream: " + e.getMessage()); } } }
Output
Hey, prepsters!
Explanation:
A string "Hey, Prepsters!" is declared.
The ByteArrayInputStream class is used to convert the string into an InputStream. The getBytes() method is called on the string to get its byte representation, which is then passed to the ByteArrayInputStream constructor.
The read() method is used in a while loop to read the data from the InputStream one byte at a time and print it to the console as a character. The loop continues until the end of the stream is reached, indicated by a return value of -1 from the read() method.
An IOException is handled using a try-catch block in case an I/O error occurs while reading from the input stream. The error message is printed to the console..
Example 2 :Java Program to Convert a String into the InputStream
Run
import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; public class Main { public static void main(String[] args) { String string = "This is a sample string"; InputStream inputStream = new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8)); int data; try { while((data = inputStream.read()) != -1) { System.out.print((char)data); } } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } } }
Output
This is a sample string
Explanation:
In this example, the string "This is a sample string" is initially declared. Using the ByteArrayInputStream class, like in the preceding example, we then generate an InputStream from this string. However, in this example, we use the StandardCharsets to indicate the character set to be used for encoding the string into a byte array. UTF 8 standard.
We use a while loop to read the data from the InputStream one byte at a time and print it to the console as a character. The loop continues until the end of the stream is reached, indicated by a return value of -1 from the read() method. The code also includes an exception handler to catch any exceptions that may occur during the reading process..
Example 3: Java Program to Convert a String into the InputStream
Run
import java.io.ByteArrayInputStream; import java.io.InputStream; public class Main { public static void main(String[] args) { String string = "PrepInsta Prime string"; byte[] byteArray = string.getBytes(); InputStream inputStream = new ByteArrayInputStream(byteArray); int data; try { while((data = inputStream.read()) != -1) { System.out.print((char)data); } } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } } }
Output
PrepInsta Prime string
Explanation:
In this example, we first declare a string "This is another sample string". We then use the getBytes() method to convert the string into an array of bytes. The ByteArrayInputStream class is then used to create an InputStream from this byte array.
We use a while loop to read the data from the InputStream one byte at a time and print it to the console as a character. The loop continues until the end of the stream is reached, indicated by a return value of -1 from the read() method. The code also includes an exception handler to catch any exceptions that may occur during the reading process.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others