InputStreamReader

In this chapter you will learn:

  1. What is InputStreamReader and how to use InputStreamReader
  2. Create InputStreamReader with encoding

Use InputStreamReader

An InputStreamReader is a bridge from byte streams to character streams. It has the following constructors.

  • InputStreamReader(InputStream in)
    Creates an InputStreamReader that uses the default charset.
  • InputStreamReader(InputStream in, Charset cs)
    Creates an InputStreamReader that uses the given charset.
  • InputStreamReader(InputStream in, CharsetDecoder dec)
    Creates an InputStreamReader that uses the given charset decoder.
  • InputStreamReader(InputStream in, String charsetName)
    Creates an InputStreamReader that uses the named charset.

The code below creates BufferedReader from InputStreamReader and URL.

import java.io.InputStreamReader;
import java.net.URL;
/*from   j  a  v a2s .c o  m*/
public class Main {
  public static void main(String[] args) throws Exception {
    URL myURL = new URL("http://www.google.com");
    InputStreamReader so = new InputStreamReader(myURL.openStream());
    while (true) {
      int output = so.read();
      if (output != -1) {
        System.out.println((char)output);
      } else {
        break;
      }
    }
    so.close();
  }
}

Create InputStreamReader with encoding

We can specify encoding when creating InputStreamReader.

import java.io.InputStreamReader;
import java.net.URL;
/*from j a va2  s.  c  om*/
public class Main {
  public static void main(String[] args) throws Exception {
    URL myURL = new URL("http://www.google.com");
    InputStreamReader so = new InputStreamReader(myURL.openStream(),"8859_1");
    while (true) {
      int output = so.read();
      if (output != -1) {
        System.out.println((char)output);
      } else {
        break;
      }
    }
    so.close();
  }
}

Next chapter...

What you will learn in the next chapter:

  1. How to use PushbackReader
Home » Java Tutorial » Reader Writer
Stream vs Reader and writer
InputStream
FileInputStream
ObjectInputStream
DataInputStream
BufferedInputStream
SequenceInputStream
PushbackInputStream
ByteArrayInputStream
PrintStream
OutputStream
FileOutputStream
DataOutputStream
ObjectOutputStream
BufferedOutputStream
ByteArrayOutputStream
FilterOutputStream
Reader
FileReader
BufferedReader
CharArrayReader
StringReader
LineNumberReader
InputStreamReader
PushbackReader
Writer
FileWriter
BufferedWriter
CharArrayWriter
StringWriter
PrintWriter
OutputStreamWriter