StringReader

Java StringReader Example

In this tutorial we will discuss about the StringReader in Java. The StringReader class represents those character streams, whose source is a string.

The StringReader class extends the Reader class, which is an abstract class for reading data from character streams. The sub-classes of the Reader class must implement the following two methods:

Finally, the StringReader class exists since the 1.1 version of Java.

The Structure of StringReader

Constructor

  • StringReader(String s)
  • Creates an instance of the StringReader class, with the specified character stream.

The StringReader in Java

The StringReader class is able to transform an ordinary string into a stream reader. Its constructor requires an input stream, which it converts to a stream. In the following example, we read a small text from a file and count its words:

StringReaderCountWordsExample.java:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.StreamTokenizer;
import java.io.StringReader;

public class StringReaderCountWordsExample {
	
private final static String FILENAME = "input.txt";
	
	public static void main(String[] args) {
		BufferedReader rd = null;
		StringReader srd = null;
		
		try {
			rd = new BufferedReader(new FileReader(FILENAME));
			
			String inputLine = null;
			StringBuilder builder = new StringBuilder();
			
			//Store the contents of the file to the StringBuilder.
			while((inputLine = rd.readLine()) != null)
				builder.append(inputLine);
			
			//Create a new tokenizer based on the StringReader class instance.
			srd = new StringReader(builder.toString());
			StreamTokenizer tokenizer = new StreamTokenizer(srd);
			
			//Count the number of words.
			int count = 0;
			while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) {
				if (tokenizer.ttype == StreamTokenizer.TT_WORD)
					++count;
			}
			
			System.out.println("The total number of words is: " + count);
		}
		catch (IOException ex) {
			System.err.println("An IOException was caught: " + ex.getMessage());
			ex.printStackTrace();
		}
		finally {
			//Close all resources.
			try {
				if(rd != null)
					rd.close();
				
				if(srd != null)
					srd.close();
			}
			catch (IOException ex) {
				System.err.println("An IOException was caught: " + ex.getMessage());
				ex.printStackTrace();
			}
		}
	}
}

First, we create an instance of the BufferedReader class, in order the contents of the specified input file. We append all read lines into an instance of the StringBuilder class, whose string value we pass as an argument to our StringReader. Finally, we use an instance of the StringTokenizer class, in order to parse the input lines and count the number of words in them.

A sample execution is shown below:

The total number of words is: 100

In the following example we follow the same logic as in our previous example, but instead of counting the number of words, we store every word in a HashMap, along with its own frequency. In case a word already exists, we increase its frequency by 1.

StringReaderWordsExample.java:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

public class StringReaderWordsExample {
	
	private final static String FILENAME = "input.txt";
	
	public static void main(String[] args) {
		BufferedReader rd = null;
		StringReader srd = null;
		Map words = new HashMap();
		
		try {
			rd = new BufferedReader(new FileReader(FILENAME));
			
			String inputLine = null;
			StringBuilder builder = new StringBuilder();
			
			//Store the contents of the file to the StringBuilder.
			while((inputLine = rd.readLine()) != null)
				builder.append(inputLine);
			
			//Create a new tokenizer based on the StringReader class instance.
			srd = new StringReader(builder.toString());
			StreamTokenizer tokenizer = new StreamTokenizer(srd);
			
			//Read and count the frequency for every word.
			while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) {
				if (tokenizer.ttype == StreamTokenizer.TT_WORD) {
					int count;
					
					if(words.containsKey(tokenizer.sval)) {
						count = words.get(tokenizer.sval).intValue();
						++count;
					}
					else
						count = 1;
					
					words.put(tokenizer.sval, count);
				}
			}
			
			System.out.println("Printing each word along with its frequency...");
			for(String key: words.keySet())
				System.out.println(key + ": " + words.get(key));
		}
		catch (IOException ex) {
			System.err.println("An IOException was caught: " + ex.getMessage());
			ex.printStackTrace();
		}
		finally {
			//Close all resources.
			try {
				if(rd != null)
					rd.close();
				
				if(srd != null)
					srd.close();
			}
			catch (IOException ex) {
				System.err.println("An IOException was caught: " + ex.getMessage());
				ex.printStackTrace();
			}
		}
	}
}

A sample execution is shown below:

Printing each word along with its frequency...
efficitur: 1
tempor: 1
suscipit: 1
...
porttitor: 1
nulla: 1

Notice that some results are missing, due to lack of space and in order for the output to be comprehensible.

Download the Eclipse Project

This was a tutorial about the StringReader in Java.

Download
You can download the full source code of this example here: StringReaderExamples.zip.

Sotirios-Efstathios Maneas

Sotirios-Efstathios (Stathis) Maneas is a PhD student at the Department of Computer Science at the University of Toronto. His main interests include distributed systems, storage systems, file systems, and operating systems.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Deborah hawes
Deborah hawes
4 years ago

Trying to sign into workday app (payroll employee app from work says connection error java.langstringcom workdroidapp???

Back to top button