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!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
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.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close