Learn how to write program in Java for reading file.
Read File in Java
This tutorial shows you how to read file in Java. Example discussed here simply reads the file and then prints the content on the console. File handling is important concept and usually programmer reads the file line by line in their applications.
Classes and Interfaces of the java.io package is used to handle the files in Java. In this example we will use following classes of java.io package for reading file:
FileReader
The class java.io.FileReader is used to read the character files. This class takes file name as a parameter. This class is used to read the character input stream. So this class (java.io.FileReader) is used to read the character file. If you have to read the raw bytes then you should use the java.io.FileInputStream class.
BufferedReader
The class java.io.BufferedReader is used to read the text from a character-input stream. This class is providing the buffering features and is very efficient in reading the characters, lines and arrays. You can also provide the buffer size or use the its default size. The default buffer size is sufficient for general purpose use.
Generally following way it is used:
BufferedReader input = new BufferedReader(new FileReader("mytextfile.txt"));
Here is the complete example of Java program that reads a character file and prints the file content on console:
import java.io.*; /** * This example code shows you how to read file in Java * */ public class ReadFileExample { public static void main(String[] args) { System.out.println("Reading File from Java code"); //Name of the file String fileName="test.text"; try{ //Create object of FileReader FileReader inputFile = new FileReader(fileName); //Instantiate the BufferedReader Class BufferedReader bufferReader = new BufferedReader(inputFile); //Variable to hold the one line data String line; // Read file line by line and print on the console while ((line = bufferReader.readLine()) != null) { System.out.println("Data is: " + line); } //Close the buffer reader bufferReader.close(); }catch(Exception e){ System.out.println("Error while reading file line by line:" + e.getMessage()); } } }
If you run the program it will give the following output:
D:\Tutorials\examples>java
ReadFileExample Reading File from Java code Data is: Line 1 Data is: Line 2 Data is: Line 3 Data is: Line 4 Data is: Line 5 Data is: Line 6 Data is: Line 7 Data is: Line 8 Data is: Line 9 Data is: Line 10 D:\Tutorials\examples> |