Nikos Maravitsas

About Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.

Java InputStreamReader Example

In this example we are going to talk about InputStreamReader Java Class. InputStreamReader is a subclass of Reader. A Reader‘s job is to connect your program to a data source, and fetch data from that source and make them available to your program for manipulation. But its purpose is to bridge the byte stream from that source to a character stream. It automatically encodes the bytes that it reads to a specified character set, like UTF-8.

So, as you can imagine, an InputStreamReader wraps around an InputStream, and “converts” the reading input stream form a byte stream to a character stream. Naturally, InputStreamReader is particularly useful when you want to read a text source, e.g a text file.

1. Obtain an InputStreamReader from a file

Let’s see how you can use an InputStreamReader to read sequences of characters form a text file.

InputStreamReaderExample.java:

package com.javacodegeeks.core.io.bufferedreader;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class InputStreamReaderExample {

    private static final String OUTPUT_FILE = "C:\\Users\\nikos\\Desktop\\TestFiles\\testFile.txt";
    public static void main(String[] args) {

        char[] chars = new char[100];

        try (InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(OUTPUT_FILE),"UTF-8")) {

            // read 100 characters from the file
            inputStreamReader.read(chars);

            System.out.println(Arrays.toString(chars));

            Arrays.fill(chars,' ') ;

            /// read 50 character from the file
            // and place them after chars[4] position in the array
            inputStreamReader.read(chars,4,50);

            System.out.println(Arrays.toString(chars));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

[a, o, s, b, c, o, i, a, c, o, i, a, n, i, s, c, n, a, o, n, c, o, a, n, s, c, n, a, o, s, n, c, o, i, a, n, c, i, o, a, n, s, c, i, a, n, c, i, a, n, s, i, c, n, a, s, i, c, n, a, s, i, o, c, n, s, a, o, i, c, n, o, a, i, s, n, c, i, o, a, n, s, c, i, o, n, a, s, o, i, c, n, i, a, s, n, c, i, a, n]
[ ,  ,  ,  , s, o, i, c, n, a, s, c, a, o, s, c, n, a, o, i, s, n, c, i, o, a, n, c, o, a, n, s, i, c, n, a, s, o, i, c, n, a, o, i, s, n, c, o, i, a, s, n, c, i,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ]

It’s fairly easy to read the whole file by packs of N characters and print them out as Strings.

InputStreamReaderExample.java:

package com.javacodegeeks.core.io.bufferedreader;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class InputStreamReaderExample {

    private static final String OUTPUT_FILE = "C:\\Users\\nikos\\Desktop\\TestFiles\\testFile.txt";
    public static void main(String[] args) {

        char[] chars = new char[100];

        try (InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(OUTPUT_FILE),"UTF-8")) {

            // read 100 characters from the file
            while (inputStreamReader.read(chars) != -1)
                System.out.println(new String(chars));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

aosbcoiacoianiscnaoncoanscnaosncoiancioanscianciansicnasicnasiocnsaoicnoaisncioanscionasoicniasncian
soicnascaoscnaoisncioancoansicnasoicnaoisncoiasncioancioasncioasc
aopscmnapsmcamcoampcmasomcaspcasc
aspcmpaosmcpas
apocsmoamcpoamscopasmcpomasopcmasopcmaosmcascpaosmcopamsc
aopscmnapsmcamcoampcmasom
caspcascaspcmpaosmcpas
apocsmoamcpoamscopasmcpomasopcmasopcmaosmcascpaosmcopamsc
aopscmnapsmcamcoa
mpcmasomcaspcascaspcmpaosmcpas
apocsmoamcpoamscopasmcpomasopcmasopcmaosmcascpaosmcopamsc
aopscmnap
smcamcoampcmasomcaspcascaspcmpaosmcpas
apocsmoamcpoamscopasmcpomasopcmasopcmaosmcascpaosmcopamsc
a
opscmnapsmcamcoampcmasomcaspcascaspcmpaosmcpas
apocsmoamcpoamscopasmcpomasopcmasopcmaosmcascpaosmco
pamsc
aopscmnapsmcamcoampcmasomcaspcascaspcmpaosmcpas
apocsmoamcpoamscopasmcpomasopcmasopcmaosmcas
cpaosmcopamsc
...

As you can see in the above example I’ve wrapped an InputStreamReader around a FileInputStream, which of course is an InputStream. This shows that you can use InputStreamReader along with any InputStream class or sub class obtained from a great variety of sources e.g a socket, a pipe , a database or even an in-memory location.

2. Obtain an InputStreamReader from the Standard Input

Let’s see how you can use InputStreamReader to read characters form the console.

InputStreamReaderExample.java:

package com.javacodegeeks.core.io.bufferedreader;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class InputStreamReaderExample {

    private static final String OUTPUT_FILE = "C:\\Users\\nikos\\Desktop\\TestFiles\\testFile.txt";
    public static void main(String[] args) {

        char[] chars = new char[100];

        try (InputStreamReader inputStreamReader = new InputStreamReader(System.in,"UTF-8")) {

           System.out.print("Type in some characters :");
            inputStreamReader.read(chars);
            System.out.println(Arrays.toString(chars));

            System.out.println(new String(chars).trim());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

Type in some characters :Java Code Geeks Rock Big Time!
[J, a, v, a,  , C, o, d, e,  , G, e, e, k, s,  , R, o, c, k,  , B, i, g,  , T, i, m, e, !, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ]
Java Code Geeks Rock Big Time!

3. Obtain an InputStreamReader from in-memory buffer

Let’s see how you can use InputStreamReader to read characters form an in-memory buffer.

InputStreamReaderExample.java:

package com.javacodegeeks.core.io.bufferedreader;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class InputStreamReaderExample {

    private static final String OUTPUT_FILE = "C:\\Users\\nikos\\Desktop\\TestFiles\\testFile.txt";
    public static void main(String[] args) {

        char[] chars = new char[100];

        String content = "Java Code Geeks Rock Big Time!";

        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {

            byteArrayOutputStream.write(content.getBytes());

            try (InputStreamReader inputStreamReader = new InputStreamReader(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()), "UTF-8")) {
                inputStreamReader.read(chars);
                System.out.println(Arrays.toString(chars));

                System.out.println(new String(chars).trim());

            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

Type in some characters :[J, a, v, a,  , C, o, d, e,  , G, e, e, k, s,  , R, o, c, k,  , B, i, g,  , T, i, m, e, !, , , , , , , , , , , , , , , , , , , , , , , , , ]
Java Code Geeks Rock Big Time!
Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books