Reading and writing character Streams in Java with Example

Character Streams are specially designed to read and write data from and to the Streams of Characters. We require this specialized Stream because of different file encoding systems. In our previous post of Byte Streams we discussed about why we should not use Byte Streams for Reading and Writing character files. Lets see this in detail and discuss about the advantages of Character Streams.



Click here to read Stream basics before continuing with Character Streams

So what should we do to read Character Streams?

We can do the read write operations using Byte Streams also but we generally avoid it because of the problem of character encoding. In Byte Streams we don’t provide any encoding scheme so if the file is not saved 8 bit character set( like ASCII or any other) format then our output would not be proper because it will treat each byte differently ( For example If a file uses UNICODE encoding system i.e. 2 bytes for a single character but byte stream will break it into two parts and to process it properly we have to apply the programming logic).
For such cases we use Character Streams which automatically translates to and from the local character set because Java conventionally use UNICODE system to store characters.

Are Character Streams ready for Internationalisation?

Absolutely, since Character Streams do the automatic conversion your program automatically adapts to the local character set and is able to read all the characters in all the languages and is ready for the Internationalization and the great thing is that you don’t have to make any extra coding effort for this. Cheers :)

Now Lets see some important methods and classes used to process Character Stream.

In Character Streams all the classes are the descendents of 2 abstract classes-
  1. Reader for reading operation.
  2. Writer for writing operation.

And the 2 most important methods in all the classes that are used for I/O operations are-
  1. public int read() throws IOException – It reads a character from Stream.
  2. public void write(int i) throws IOException – it writes the Character into the Stream. Data into 16 lower bits are converted into characters and higher 16 bits are ignored.

Now lets have a look at Some Important classes for Byte Streams

Stream class
BufferedReaderHandles buffered input stream.
BufferedWriterHandles buffered output stream.
FileReaderInput stream that reads from file. (Not recommended)
FileWriterOutput stream that writes to file. (Not recommended)
InputStreamReaderInput stream that translate byte to character (Recommended)
OutputStreamReaderOutput stream that translate character to byte. (Recommended)
PrintWriterOutput Stream that contain print() and println() method.
ReaderAbstract class that define character stream input
WriterAbstract class that define character stream output

File Reading and Writing Example using Character Streams

  • You can read any text file using this program but ensure that the file is in classpath or provide a fully qualified pathname of the file.
  • Also we are using Java 7 feature named try with resources in which we are declaring and Initializing both the Streams along with try and we don’t need to close them explicitly but ensure that every resource you initialize inside try should implement AutoClosable interface.
  • In this example we will use InputStreamReader and OutputStreamWriter instead of FileReader and FileWriter because –
    • InputStreamReader and OutputStreamWriter are basically a bridge between Byte Stream and Character Stream and hence can process any type of input stream like network connections, zip files etc including files.
    • These classes also accept the user defined encoding and hence it does not depends only on default platform encoding which make FileReader and FileWriter classes pretty much useless and often results in corrupted data when the code is run on systems with different platform default encodings. This condition can be escaped by using correct encoding in InputStreamReader and InputStreamWriter.
package codingeekExamples;

import java.nio.charset.UnsupportedCharsetException;

public class CharacterStreamExample {

    public static void main(String[] args) throws IOException {

        try (
        // Declaring and initializing both the Streams inside try so that there
        // is no need to close them. You can do this with many other classes but
        // make sure that they all implements the AutoClosable Interface
                Reader reader = new InputStreamReader(new FileInputStream("input.txt"), "UTF-8");
                Writer writer = new OutputStreamWriter(new FileOutputStream("output.txt"), "UTF-8");
            ) {
            Integer c;

            // Reading and Writing single character at a time until end of file
            // is reached
            while ((c = != -1) {
            System.out.println("File Written successfully");
            // Handling exceptions thrown by Streams to ensure that our program
            // ends in a user friendly way
        } catch (FileNotFoundException e) {
            System.out.println("File not found");
        } catch (UnsupportedCharsetException e) {
            System.out.println("Given charset is unsupported");

You can also use BufferedReader and BufferedWriter so as to read the data in bulk like reading a complete line on one go.

Resources:-   Oracle Character Streams

Happy Learning :)

  • xpecial

    Failing is also bad karma,so you must copy :(