Character-based streams read and write 16-bit Unicode characters. With Unicode characters, it is easier to write programs, which will function with character sets other than ASCII. Java’s character-based stream classes buffer their data more efficiently than most of the byte-based input output classes. Character stream classes descend from the abstract classes Reader and Writer.
Reading Character Streams
With the byte-oriented streams, you can read either a single byte or an array of bytes; but with the character-based streams, you can read lines of text. A line of text is a series of characters terminated with a carriage return or carriage return and linefeed. Data can be read from and written to text files.
Reader class and its descendants can be used to read character streams. The methods of java.io.reader are similar to the methods of the java.io.InputStream class.
Hierarchy for Reader class
The FileReader class reads text files, using the platform’s default character encoding and the buffer size. If you wish to change these settings, you can use the InputStreamReader class.
public FileReader(String filename) throws FileNotFoundException
public FileReader(File file) throws FileNotFoundException
public FileReader(FileDescriptor fdescriptor)
Methods in FileReader class are inherited from Reader class or InputStream Reader class. Commonly used methods in this class are:
read(char) Reads character into arrays
read() Reads a single character
close() Closes the stream
BufferedReader class buffers data into accessible units. It provides the readLine method, which returns a String
public class reader
public static void main (String args)
FileReader input = new FileReader("Demo.txt");
BufferedReader bufferInput = new BufferedReader(input);
while ((line = bufferInput.readLine()) != null)
System.out.println("Read: " +line);
catch (IOException e)
In the above code, FileReader object “input” is created by using the constructor FileReader(“Demo.txt”), where Demo.txt is a text file to be read. The FileReader object (“input”) is passed as an argument to the constructor BufferedReader(input), which is used for buffering the data into accessible units. Instead of reading or writing byte by byte, an entire line is read into the String variable called line, by using BufferReader’s readLine() method. The readLine() method returns null, upon encountering end-of-file, instead of returning –1 (as in other byte stream input classes). Here, it reads line by line input from the file Demo.txt and writes the output to the console.
The InputStreamReader class serves as a bridge between the byte streams and character streams. It reads bytes from the input stream and converts it into the characters.