Convert String to Stream of Chars in Java
Last Updated :
26 Jan, 2024
The StringReader class from the java.io package in Java can be used to convert a String to a character stream. When you need to read characters from a string as though it were an input stream, the StringReader class can be helpful in creating a character stream from a string.
In this article, we will learn to convert a String to a char stream in Java.
Java Program to Convert String into Char Stream
Below is the implementation of Converting String to Char Stream:
Java
import java.io.IOException;
import java.io.StringReader;
public class StringToCharStreamExample {
public static void main(String[] args)
{
String inputString = "Geeks For Geeks" ;
StringReader stringReader
= new StringReader(inputString);
try {
int charValue;
while ((charValue = stringReader.read())!= - 1 ) {
char character = ( char )charValue;
System.out.print(character);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
stringReader.close();
}
}
}
|
Output:
Geeks For Geeks
The input string “Geeks For Geeks” is converted into a character stream using the StringReader, and each character is then written to the terminal.
Explanation of the above Program:
Step 1: Take Input from the User.
String inputString = "Geeks For Geeks";
You wish to turn the string “Geeks For Geeks” into a character stream, therefore this line initializes a String variable called inputString with that value.
Step 2: Initialising the StringReader Object
StringReader stringReader = new StringReader(inputString);
Here, the input string is used to build a StringReader object with the identifier stringReader. You can read characters from a string as if it were an input stream by using this class.
Step 3: Using StringReader to convert Input String into Char Stream
int charValue;
while ((charValue = stringReader.read()) != -1) {
char character = (char) charValue;
System.out.print(character);
}
This section of the code loops through each character in the string using a while loop. To read characters from the StringReader, use the read() function. When read() returns -1, the loop ends. This happens till the end of the stream. Every character is cast to a char inside the loop before being printed to the console.
Share your thoughts in the comments
Please Login to comment...