HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / I/O / Java FileReader

Java FileReader

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. FileReader class

  • It is meant for reading streams of characters.
  • It is part of java.io package.
  • It extends InputStreamReader class.
  • It implements Closeable, AutoCloseable and Readable interfaces.
  • If not provided, it uses the platform’s default charset.
  • It uses a default buffer size for reading the files.

2. Creating a 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. Creating FileReader using the name of the file

import java.io.FileReader;

//Create an instance in the application code
String fileName = "c:\temp\test.txt";
FileReader input = new FileReader(fileName);

2.2. Creating FileReader using the File object

import java.io.File;
import java.io.FileReader;

//Create an instance in the application code
File file = new File("c:\temp\test.txt");
FileReader input = new FileReader(file);

2.3. Specifying character encoding

Above both examples create the file reader instance with the default character encoding. To specify the a different character encoding, we can pass the encoding information as Charset in the second argument to both constructors.

FileReader input = new FileReader(fileName, Charset.forName("UTF8"));

//or 

FileReader input = new FileReader(file, Charset.forName("UTF8"));

3. Java FileReader Example

Lets see a few examples to read a file using the FileReader in Java.

Example 1: Reading a file using FileReader

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.

import java.io.FileReader;
import java.io.IOException;

public class FileReaderExample 
{
	public static void main(String[] args) throws IOException
	{
		String fileName = "demo.txt";
		
		FileReader fileReader = new FileReader(fileName);
		
	    try {
	    	char [] a = new char[2048];
			fileReader.read(a);   
		      
		    for(char c : a) {
		    	System.out.print(c);   
		    }
		} finally {
			fileReader.close();
		}
	}
}

Program output:

hello world 1
hello world 2
hello world 3

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

import java.io.FileReader;
import java.io.IOException;

public class FileReaderExample 
{
	public static void main(String[] args) throws IOException
	{
		String fileName = "demo.txt";
		
		FileReader fileReader = new FileReader(fileName);
		
		try {
	    	 int i;    
	         while((i = fileReader.read()) != -1) {
	         	System.out.print((char)i);    
	         }
		} finally {
			fileReader.close();
		}
	}
}

Program output:

hello world 1
hello world 2
hello world 3

Example 3: Reading a file line by line using FileReader

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().

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

public class FileReaderExample 
{
	public static void main(String[] args) throws IOException
	{
		String fileName = "demo.txt";
		
		BufferedReader br = new BufferedReader(new FileReader(fileName));
		
		try {
		    String line;
		    while ((line = br.readLine()) != null) {
		       System.out.println(line);    
		    }
		} finally {
		    br.close();
		}
	}
}

Program output:

hello world 1
hello world 2
hello world 3

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Java IO

  • Java IO Introduction
  • Java How IO works?
  • Java IO vs NIO
  • Java Create File
  • Java Write to File
  • Java Append to File
  • Java Read File
  • Java Read File to String
  • Java Read File to Byte[]
  • Java Make File Read Only
  • Java Copy File
  • Java Copy Directory
  • Java Delete Directory
  • Java Current Working Directory
  • Java Read/Write Properties File
  • Java Read File from Resources
  • Java Read File from Classpath
  • Java Read/Write UTF-8 Data
  • Java Check if File Exist
  • Java Create Temporary File
  • Java Write to Temporary File
  • Java Delete Temporary File
  • Java Read from Console
  • Java Typesafe input using Scanner
  • Java Password Protected Zip
  • Java Unzip with Subdirectories
  • Java Generate SHA/MD5
  • Java Read CSV File
  • Java InputStream to String
  • Java String to InputStream
  • Java OutputStream to InputStream
  • Java InputStreamReader
  • Java BufferedReader
  • Java FileReader
  • Java LineNumberReader
  • Java StringReader
  • Java FileWriter
  • Java BufferedWriter
  • Java FilenameFilter
  • Java FileFilter

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces