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 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

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