Java has several File IO classes for reading and writing into the files. Each class has its own advantages. This example illustrates how to use FileReader for reading a text file. The main purpose of using the FileReader is to read the text content from a file where FileInputStream is used for reading the stream of bytes from a file. In short, ASCII is a text file which will be read by using the FileReader and binary file will be read using the FileInputStream. If the text file is very huge, you could use the BufferedReader on top of the FileReader to improve the performance.
Lets look at the simple example on how to use FileReader class.
FileReader Example
package javabeat.net.core; import java.io.File; import java.io.FileReader; import java.io.IOException; /** * FileReader Example * * @author Krishna * */ public class FileReaderExample { public static void main (String args[]) throws IOException{ //Initialize char array char[] chars = new char[100]; char[] chars1 = new char[100]; //Create File object File file = new File("TextFile.txt"); //Create FileReader instance FileReader fileReader = new FileReader(file); //Read characters and assign to character array fileReader.read(chars); System.out.println(chars); //Close the stream fileReader.close(); //Reading through character fileReader = new FileReader(file); int character = fileReader.read(); while (character != -1){ System.out.println(character); character = fileReader.read(); } //Close the stream fileReader.close(); } }
TextFile.txt
Reading the text content using FileReader!!
Output…
Reading the text content using FileReader!! 82 101 97 100 105 110 103 32 116 104 101 32 116 101 120 116 32 99 111 110 116 101 110 116 32 117 115 105 110 103 32 70 105 108 101 82 101 97 100 101 114 33 33