Open In App

Convert String to Stream of Chars in Java

Last Updated : 26 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




// Java Program to Convert String into Char Stream
import java.io.IOException;
import java.io.StringReader;
  
// Driver Class
public class StringToCharStreamExample {
      // Main Function
    public static void main(String[] args)
    {
        // Your input string
        String inputString = "Geeks For Geeks";
  
        // Create a StringReader object with the input
        // string
        StringReader stringReader
            = new StringReader(inputString);
  
        try {
            // Read characters from the StringReader and
            // print them
            int charValue;
            while ((charValue = stringReader.read())!= -1) {
                char character = (char)charValue;
                System.out.print(character);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            // Close the StringReader to release resources
            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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads