How Do I Read A Text File Through Java Code ?


Hello friends, Lets begin with another source code in java with example and explanation. Today, I am posting a hub on Java Source Code category with program "How do I read a text file in Java "?. Learning Java by example is fun. To run below code you must have JDK installed along with some basic knowledge, How to compile a Java program ?. , How to run a Java program.? and some basic Java fundamentals. Lets begin first writing the source code and then explaining the code step-by-step in a tutorial form.

Given below is the snap shot of

the student.txt file from which our source code reads the data and prints out to console window. Remember the path given in the program as "E:\student.txt" is the path where I have kept student.txt file. You can place the file wherever you want on your machine, but just replace the path in the Java program to yours.

How do i read text file in Java ?


public class Reader {
public static void main(String[ ] args) {
File file = new File("E:\student.txt");
BufferedReader reader = null;
StringBuilder line = new StringBuilder();

try {
reader = new BufferedReader(new FileReader(file));
String text = null;

while ((text = reader.readLine()) != null) {
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
try {
if (reader != null) {
} catch (IOException e) {

Working of Example

Lets look at the code above line by line. I will be explaining you what each line does. I will be taking you with little-little snippets and explaining overall functionality of the source code.

Line 1 to 5 -

Basically it contains import statements for the classes required by our source code to get executed by printing the text. The imports are generally from the I/O package libraries. Our code uses these classes in the program below. Some of them are main classes of I/O package such as BufferedReader, File, FileReader, FileNotFoundException and IOException.

Line 9 to 11 -

If we look at line 9, we will find that a new file is created on the path "E:\student.txt", if no file exists. But in our case file is already placed on the path with some content written on it. This file we gave as a string to just create an object of class File not a file on system. Line 10 creates a null BufferedReader object. Generally BufferedReader is an class which acts as a buffer to hold chunks of character data. This class we need because its fast and it reads character data fast with large chunks of storage.Line 11 we create a StringBuilder object because this variable will store all the data present in student.txt document and prints it on the console.

Line 13 to 15 :-

Line 13 starts with a try-catch-finally block, generally when we deal with the I/O files many exceptions can occur. To catch such exceptions we must put our code in try-catch-finally block. Line 14 we create a BufferedReader object which wraps up a newly created FileReader object to which holds our File object to read

the data. Generally FileReader object can read stream of characters from a file. FileReader can read characters from the student.txt file provided to it by File object. Line 15 creates a null string with a text variable , this variable is temporary placeholder or say counter for the next while loop. It will hold chunk of character on which while loops places a test condition.

Line 17 to 19 :-

Line 17 starts with a while loop. As we have access to file student.txt by FileReader object to read the file and its wrapper class BufferedReader class which holds FileReader class to process information transfer and storage fast. while loop applies looping on Counter variable text which holds the line by line data of character. This line of characters is been provided to text variable by method called as readLine() defined in BufferedReader class. This method reads and outputs character with one full line. The test condition in while loop makes it loop till text variable outputs null. On line 18 and 19 each loop will hold one-one line of characters in line variable by append() method. Generally append() method is defined in StringBuilder class which performs the task to append two strings together. As soon as one line gets stored in line variable we need one line separator which shifts line variable to hold string now from next line. So to get that line separator we put code that places line separator by the System properties called as line.separator.

Line 21 to 25 :-

Here we used try-catch statement because there may come a exception when say file student.txt is not found on the path specified in the code i.e 'E:\student.txt', so it throws FileNotFoundException. If there is any exception occured while transferring of characters IOException may occur.

Line 26 to 34 :-

Generally try-catch-finally occur together. Here finally is optional but most important, it gets executed once in code whether exception occurs or not. All the resource releasing code is written in finally block. Since BufferedReader object holds critical resource for I/O operation, we should release it in our code. Its generally good practice to release the critical resources.

Line 35 : -

After all iterations and appending of characters line-by-line in line variable , we use print statement to print all the character of file on the console.

For more of such hot topics read my other posts here :

Visit my new website

Article Written By jontymagicman

I am DInesh Varyani.

Last updated on 26-07-2016 125 0

Please login to comment on this post.
There are no comments yet.
Experts Classification Of Essays
Java As A Programming Platform