Java FileReader
class can be used to read data (stream of characters) from files. In this tutorial, we will learn about FileReader
class, its constructors, methods and usages with the help of examples.
1. Introduction
The FileReader
class is:
- meant for reading streams of characters.
- part of
java.io
package. - extends
InputStreamReader
class. - implements
Closeable
,AutoCloseable
andReadable
interfaces. - if not provided, it uses the platform’s default charset.
- uses a default buffer size for reading the files.
2. Creating FileReader
To use the FileReader
in the application, we must first import it from package java.io
using the import statement. For creating the instance of FileReader
, use one of its constructors.
2.1. Using File Name
2.2. Using File
2.3. Character Encoding
Above both examples create the file reader instance with the default character encoding. To specify a different character encoding, we can pass the encoding information as Charset
in the second argument to both constructors.
3. FileReader Examples
Let us see a few examples of reading a file using the FileReader
in Java.
3.1. Reading a Small Text File in char[]
In the given example, we are reading a text file. The file contains 3 small hello world messages. Here we are attempting to read the file in single read()
operation so make sure you create a sufficiently large char[]
to store all the content on the file.
This should be used only for small text files.
3.2. Reading a File One Character at a Time
In the given example, we are using the read()
method which reads a single character from the file and returns it. When all the content of the file has been read, it returns -1
which indicates the end of the file.
3.3. Reading a File Line by Line
FileReader
does not directly support reading a file line by line. For this, we need to wrap the FileReader
inside a BufferedReader
instance which provides the method readLine()
.
Happy Learning !!