Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
reader/writer
communitycreator

What are OutputStreamWriter and InputStreamReader?

Shadrach Adamu

OutputStreamWriter

OutputStreamWriter is a subclass of Writer:

It is a bridge which allows you to convert a byte stream into a character stream. In other words, it allows you to convert an OutputStream into a Writer.

How the OutputStreamWriter works

Each time the write() method of OutputStreamWriter is called, a call to the encoding converter of the specified character will be called. The resulting bytes are buffered before being written to the underlying output stream. Although the size of this buffer can be customized, it is often large enough for most applications. It is important to note that the characters given to the write() method are not buffered.

How to create an OutputStreamWriter

To create an OutputStreamWriter, we must first import the java.io.OutputStreamWriter package. After importing the package, we can create an OutputStreamWriter as shown below.

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
class OutputStreamWriterExample {
    public static void main( String args[] ) {
        try{
        File path = File.createTempFile("output", ".txt");
        // Creates an OutputStream
        FileOutputStream file = new FileOutputStream(path);
        // Creates an OutputStreamWriter
        OutputStreamWriter output = new OutputStreamWriter(file);
        System.out.println("Successfully written into "+output);
        }catch(Exception e)
        {
            e.getStackTrace();

            }
        
    }
}
How to create OutputStreamWriter using the default character encoding?

The file is named by FileOutputStream. Here, we use standard character encoding to write characters to the output stream. However, we can specify the character encoding type (UTF-8 or UTF-16) which will be used to write the data. To provide the kind of character encoding, we used the Charset class.

// Creates an OutputStreamWriter specifying the character encoding
OutputStreamWriter output = new OutputStreamWriter(file, Charset.forName ("UTF8");  
How to specify a character encoding for an OutputStreamWriter
main.java
output.txt
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
class OutputStreamWriterExample {
    public static void main( String args[] ) {
      String data = "This is a line of text inside the file.";
try {
            // This Creates a FileOutputStream
            File file = File.createTempFile("output", ".txt");
            //FileOutputStream file = new FileOutputStream("output.txt");

            // This Creates an OutputStreamWriter
            OutputStreamWriter output = new OutputStreamWriter(new FileOutputStream(file));

            // This Writes string to the file
            output.write(data);
            System.out.println("Successfully written to " + file.getCanonicalPath());

            // This Closes the writer
            output.close();
        } catch (Exception e) {
            e.getStackTrace();
        }
    }
}
An Example: How to use OutputStreamWriter to write data to a file

The OutputStreamWriter methods

Various OutputStreamWriter methods
Various OutputStreamWriter methods

InputStreamReader

InputStreamReader is a reader subclass:

It’s a converter for converting byte streams to character streams. To put it another way, it allows you to convert the InputStream into a reader. For example, some characters require two bytes to store. To read such data, use an InputStreamReader, which reads two bytes together and translates them to appropriate characters.

How the InputStreamReader works

One or more bytes will be read from the underlying input byte stream with each call to one of InputStreamReader's read() functions. More bytes from the underlying stream can be read than are required for the current read operation, ensuring efficient byte-to-character translation. The character set to be used can be named or explicitly stated, or the platform’s standard character set can be utilized.

How to create an InputStreamReader

To create an InputStreamReader, we must first import the java.io.InputStreamReader package. After importing the package, we can create such an input stream reader.

import java.io.*;
import java.nio.charset.Charset;
import java.io.InputStreamReader;
class InputStreamReaderExample{
    public static void main( String args[] ) {
        try{
         File path = File.createTempFile("output", ".txt");
        // Creates an InputStream
        FileInputStream file = new FileInputStream(path);
        // Creates an InputStreamReader
        InputStreamReader input = new InputStreamReader(file);
        System.out.println("Successfully read from the file");
        } catch (Exception e) {
            e.getStackTrace();
        }
    }
}
How to create an InputStreamReader using the default character encoding

In the above example, we created an InputStreamReader named input and a FileInputStream named file. This is the location in the file where the data is stored in the standard character encoding, but we can also specify the character encoding type (UTF-8 or UTF-16) in the file.

// This Creates an InputStreamReader specifying the character encoding
InputStreamReader input = new InputStreamReader(file, Charset.forName("UTF-8"));
How to specify character encoding for an InputStreamReader

Here we use the Charset class to specify the character encoding in the file. Let’s try to read this file using InputStreamReader.

main.java
text.txt
import java.io.*;

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

    // This Creates an array of character
    InputStream input = new FileInputStream("text.txt");

        try(InputStreamReader inputStreamReader =
                    new InputStreamReader(input)){

            int data = inputStreamReader.read();
            while(data != -1) {
                System.out.print((char) data);
                data = inputStreamReader.read();
            }

        }

  }
}
How to use InputStreamReader to read from a file input.txt?
OutputStreamWriter and InputStreamReader
OutputStreamWriter and InputStreamReader

The InputStreamReader methods:

Various InputStreamReader methods
Various InputStreamReader methods

Summary

The InputStreamReader and OutputStreamWriter conversion streams convert between the character and byte streams using the provided character set encoding or a standard local encoding scheme. Because they allow the consistent use of current 8-bit character encodings for local character sets, these classes are referred to as the "glue". They use the input byte stream as a source and create UTF-16 characters. The OutputStreamWriter creates a byte-encoded UTF-16 character form that is written to the byte output stream as the target.

RELATED TAGS

java
reader/writer
communitycreator
RELATED COURSES

View all Courses

Keep Exploring