filereader-used-for-reading-file-in-java-File-handling
admin
FileReader in Java: A Complete Guide with Examples
Updated: February 13, 2025 by Shubham mishra
The FileReader
class in Java is part of the java.io
package and is used to read data from files. It is a convenient way to read character-based data from a file, such as text files. In this tutorial, we will explore how to use the FileReader
class with practical examples and best practices.
FileReader
reads data character by character, making it ideal for text files.
The following example demonstrates how to read a file character by character using the FileReader
class:
import java.io.*;
class FileExample3 {
public static void main(String args[]) {
FileReader fr = null;
try {
fr = new FileReader("D:/Assignments/message.txt");
int ch;
while ((ch = fr.read()) != -1) {
System.out.print((char) ch);
}
} catch (FileNotFoundException fnf) {
System.out.println("Cannot open the file");
} catch (IOException ex) {
System.out.println("Error while reading file");
} finally {
if (fr != null) {
try {
fr.close();
} catch (IOException ex) {
System.out.println("Error while closing file");
}
}
}
}
}
In this example:
FileReader
is used to open the file message.txt
.read()
method reads one character at a time until the end of the file (-1
is returned).
The following example shows how to read an entire file into a string using the FileReader
class:
import java.io.*;
class FileExample3 {
public static void main(String args[]) {
FileReader fr = null;
try {
fr = new FileReader("D:/Assignments/message.txt");
File fobj = new File("D:/Assignments/message.txt");
int sz = (int) fobj.length();
char[] arr = new char[sz];
fr.read(arr);
String s = new String(arr);
System.out.println(s);
} catch (FileNotFoundException fnf) {
System.out.println("Cannot open the file");
} catch (IOException ex) {
System.out.println("Error while reading file");
} finally {
if (fr != null) {
try {
fr.close();
} catch (IOException ex) {
System.out.println("Error while closing file");
}
}
}
}
}
In this example:
File
class is used to determine the size of the file.read()
method reads the entire file into the array, which is then converted to a string.finally
block or try-with-resources to ensure the file is closed after reading.FileNotFoundException
and IOException
to avoid runtime errors.FileReader
in a BufferedReader
.
The FileReader
class in Java is a powerful tool for reading character-based data from files. By following the examples and best practices outlined in this tutorial, you can efficiently handle file operations in your Java applications. As you progress, consider exploring advanced topics like BufferedReader
, FileWriter
, and Java's NIO package for more robust file handling.
Practice coding regularly, work on small projects, and explore Java's extensive standard library to become proficient in file handling. Best of luck on your coding journey!