Ebooks

Java InputStreamReader tutorial

Java InputStreamReader tutorial shows how to use Java InputStreamReader to read text in Java.

Java JavaInputStreamReader

JavaInputStreamReader is a bridge between byte streams and character streams. It reads bytes and decodes them into characters using a specified charset.

It is recommended to wrap an InputStreamReader within a BufferedReader for optimal efficiency.

Note that when working with character streams in Java, we should avoid using streams that rely on default encoding, such as FileReader or PrintWriter.

Java InputStreamReader file stream

In the first example, we use InputStreamReader to read text from a file stream.

russiantext.txt
Пе́рвая мирова́я война́ (28 июля 1914 — 11 ноября 1918) — один 
из самых широкомасштабных вооружённых конфликтов в истории человечества.
Формальным поводом к войне послужили события в Сараеве, 
где 28 июня 1914 года девятнадцатилетний боснийский серб, студент 
Гаврило Принцип осуществил покушение, в результате которого был убит 
австрийский эрцгерцог Франц Фердинанд и его морганатическая жена София Хотек.

We have a text in Cyrillic.

JavaInputStreamReaderEx.java
package com.zetcode;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class JavaInputStreamReaderEx {

    public static void main(String[] args) throws FileNotFoundException, IOException {
       
        String fileName = "src/main/resources/russiantext.txt";

        try (FileInputStream fis = new FileInputStream(fileName);
                InputStreamReader isr = new InputStreamReader(fis, 
                    StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr)) {

            String line;


            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        }
    }
}

The example reads a small text in Russian located in the src/main/resources directory.

try (FileInputStream fis = new FileInputStream(fileName);
        InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
        BufferedReader br = new BufferedReader(isr)) {

A FileInputStream is used to create a file stream. The FileInputStream is wrapped into a InputStreamReader for reading text data. We set the StandardCharsets.UTF_8 encoding. Finally, the InputStreamReader is wrapped into a BufferedReader for optimal efficiency.

Java InputStreamReader standard input stream

The second example uses InputStreamReader to read text from standard input stream.

JavaInputStreamReaderEx2.java
package com.zetcode;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class JavaInputStreamReaderEx2 {

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

        try (BufferedReader bin
                = new BufferedReader(new InputStreamReader(System.in, 
                        StandardCharsets.UTF_8))) {

            String line;

            System.out.print("Give me a cookie: ");
            
            while (!(("cookie").equals(line = bin.readLine()))) {
                
                System.out.println(line);
                System.out.print("Give me a cookie: ");
            }
        }
    }
}

The example prints a prompt and awaits a response from the user. The program ends when it receives the correct input.

try (BufferedReader bin
        = new BufferedReader(new InputStreamReader(System.in))) {

We use System.in to read from standard input.

Java InputStreamReader URL stream

The following example reads text from a network stream with InputStreamReader.

JavaInputStreamReaderEx3.java
package com.zetcode;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class JavaInputStreamReaderEx3 {

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

        StringBuilder sb;

        URL url = new URL("http://www.something.com");

        try (InputStreamReader isr = new InputStreamReader(url.openStream(),
                StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr)) {
            
            String line;

            sb = new StringBuilder();

            while ((line = br.readLine()) != null) {

                sb.append(line);
                sb.append(System.lineSeparator());
            }
        }

        System.out.println(sb.toString());
    }
}

The example reads text from a website.

try (InputStreamReader isr = new InputStreamReader(url.openStream(),
        StandardCharsets.UTF_8);
        BufferedReader br = new BufferedReader(isr)) {

The example opens a stream from the specified URL. It reads HTML code from the something.com webpage.

The next example calls an Alexa webservice to determine the ranking of a website.

JavaInputStreamReaderEx4.java
package com.zetcode;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class JavaInputStreamReaderEx4 {

    public static void main(String[] args) throws MalformedURLException,
            IOException, ParserConfigurationException, SAXException {

        String webSite = "www.something.com";

        int ranking = 0;

        String url = String.format("http://data.alexa.com/data?cli=10&url=%s", 
                webSite);

        URLConnection conn = new URL(url).openConnection();

        try (InputStream is = conn.getInputStream()) {

            DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();

            Document doc = builder.parse(is);

            Element element = doc.getDocumentElement();

            NodeList nodeList = element.getElementsByTagName("POPULARITY");

            if (nodeList.getLength() > 0) {

                Element elementAttribute = (Element) nodeList.item(0);

                ranking = Integer.valueOf(elementAttribute.getAttribute("TEXT"));
            }
        }

        System.out.printf("Ranking of %s: %d%n", webSite, ranking);
    }
}

The example receives an XML input and uses Java DOM parser to parse it.

NodeList nodeList = element.getElementsByTagName("POPULARITY");

if (nodeList.getLength() > 0) {

    Element elementAttribute = (Element) nodeList.item(0);

    ranking = Integer.valueOf(elementAttribute.getAttribute("TEXT"));
}

The ranking is available in the POPULARITY tag's TEXT attribute.

In this tutorial, we have shown how to work with Java InputStreamReader to read text in Java. You might also be interested in the related tutorials: Java FileInputStream tutorial, Java InputStream tutorial, Reading text files in Java, Jsoup tutorial, and Java tutorial.