Home » Core Java » io » FileReader » Java FileReader Example

About Nikos Maravitsas

Nikos Maravitsas
Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. 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 FileReader Example

In this example we are going to see how to use FileReader Java class in order to read characters from a file. As you might remember from a previous FileInpustream Example it is easy to wrap an InputStream, that creates an input byte stream, to a Reader class that bridges a byte stream to a character stream. To be more convenient, Java offers FileReader that directly connects a file to an input character stream, so you can directly read characters from it.

Let’s see some examples:
 
 
 

1. Simple FileReader Examples

FileReaderExample.java:

package com.javacodegeeks.core.io.outputstream;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

public class FileReaderExample {

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

        char[] chars = new char[100];
        char[] chars2 = new char[100];

        try (FileReader fileReader = new FileReader(new File(OUTPUT_FILE))) {

            // read a single bytes
            int r =  fileReader.read();
            System.out.println("Read byte :" +r);

            // read a sequence of bytes and store it to a char[] array
            int charsRead = fileReader.read(chars);
            System.out.println("Read bytes : "+charsRead);
            System.out.println(Arrays.toString(chars));

            // read a sequence of bytes and store it to arbitrary position to a char[] array
            charsRead = fileReader.read(chars2,5,30);
            System.out.println("Read bytes : "+charsRead);
            System.out.println(Arrays.toString(chars2));

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

This is the output:

Read byte :105
Read bytes : 100
[a, s, i, d, a, i, o, s, d, h, i, o, h, a, d, h, a, i, s, h, f, a, i, s, h, f, o, i, a, h, f, o, i, a, s, f, a, i, s, h, f, o, i, h, a, o, s, f, i, h, o, a, s, f, a, s, i, f, h, o, a, h, s, f, o, i, h, a, s, i, o, f, h, a, i, s, h, f, o, a, i, s, h, f, i, o, a, h, f, i, o, a, s, h, f, o, i, a, s, h]
Read bytes : 30
[, , , , , f, o, i, a, h, s, o, i, f, i, a, j, s, f, j, a, i, o, j, f, o, a, j, s, f, o, i, a, j, s,  , , , , , , , , ,  , , , , , , , , , ]

As you can see, it’s very easy to read characters from the file and store it into a char[] array. You can either choose to read a single character, or a sequence of characters, which you can either use to fill up a char array or store it in an arbitrary offset in the char array.

2. Buffering a FileReader Examples

Of course you can also buffer an FileReader using an BufferedReader. If your application is very I/O intensive and it intends to read large amounts of data from large files, then it’s highly advised to buffer the FileReader. For that, you can use a BufferedReader. This will automatically create an internal buffer and perform as less I/O operations as possible. You can also choose the internal buffer size.

BufferedReader offers a very convenient readLine method that enables to read character streams line by line. I

Let’s see how you can read a text file line by line :

FileReaderExample.java:

package com.javacodegeeks.core.io.outputstream;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class FileReaderExample {

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

        String str = "";
        try (BufferedReader bufReader = new BufferedReader(new FileReader(new File(OUTPUT_FILE)),1024)) {

            while ( (  str = bufReader.readLine() ) != null )
                System.out.println(str);

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

This is the output:

aoifjaiofjaoisfjaoisjaosijfaoisjfoiasjfioasjinoasjcniajna]aifja]fa]sfafa
asfajsifjaoisjfoiiasidaiosdhiohadhaishfaishfoiahfoiasfaishfoihaosfihoasf
asifhoahsfoihasiofhaishfoaishfioahfioashfoiashfoiahsoif
iajsfjaiojfoajsfoiajsoifajsoifjasfjsajfoasjfoiasjfoisajfoia
oiasjfojaoifjaiofjaoisfjaoisjaosijfaoisjfoiasjfioasjinoasjcniajna]aifja]fa]sfafa
iasidaiosdhiohadhaishfaishfoiahfoiasfaishfoihaosfihoasf
asifhoahsfoihasiofhaishfoaishfioahfioashfoiashfoiahsoif
iajsfjaiojfoajsfoiajsoifajsoifjasfjsajfoasjfoiasjfoisajfoia
oiasjfojaoifjaiofjaoisfjaoisjaosijfaoisjfoiasjfioasjinoasjcniajna]aifja]fa]sfafa
asfajsifjaoisjfoiiasidaiosdhiohadhaishfaishfoiahfoiasfaishfoihaosfihoasf
...

Download source code

This was a Java FileReader Example. You can download the source code of this example here : FileReaderExample.zip

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 our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

Want to take your Java Skills to the next level?
Grab our programming books for FREE!
  • Save time by leveraging our field-tested solutions to common problems.
  • The books cover a wide range of topics, from JPA and JUnit, to JMeter and Android.
  • Each book comes as a standalone guide (with source code provided), so that you use it as reference.
Last Step ...

Where should we send the free eBooks?

Good Work!
To download the books, please verify your email address by following the instructions found on the email we just sent you.