Danson Wachira is a certified Trainer in Computer Science, Information Technology and related studies.
Lesson 34: How to read a text file in Java
Using programming skills to read, write or just manipulate text files is a vital hands-on skill in programming. A text file is just a file with text in it. Such files can be created easily in text editors such as Notepad in Microsoft Windows, TextEdit in Mac or Gedit in Linux.
Text files have many uses in programming such as storing program passwords, presenting program documentation to users or just holding important information such as table structures, schema or file formats.
To start with, we are going to create a new project for this lesson. On the Java NetBeans menu bar click on File and select “New Project.” For the purpose of uniformity and so that you follow easily, call the project “TextFiles.”
Since we anticipate some errors in the program, it is a good programming practice to trap those Exceptions and handle them in the main class. Add the following line of code into the class:
The main class should be able to trap errors so the class should look as shown below with the added statement to trap Exceptions:
Notice the import statement: import java.io.IOException; before the class and throws IOException in the main class. This alerts Java that Exceptions might occur in the program. We’ll use try … catch block later to handle these Exceptions. If you have not yet visited the topic about Java Exceptions, I recommend you do so first.
To read a text file, we’ll dedicate another class to do so. Create a new class and call it ReadFile. The Read File class should look as shown below with import statements:
Don’t worry about the yellow lines, this is just a Java NetBeans feature to denote unused methods or variables in a program. We’ll need an object of this class to read the file and we’ll also need to create a constructor. Together with these, we’ll add two more methods; one to read the file path and another to return the text as an array of characters. Modify the class so that it will look like shown below:
Again, don’t worry about the red line, it will disappear once we declare a return statement. Notice the "throws IOException" statement to the end of the method header.
Methods that manipulate, read or write text files in Java programming require that Exceptions should be handled. Java will throw Exceptions on the "throws IOException" statement where the main method catch and handle them.
To read text, we are going to use a Java method called FileReader that reads bytes from a text file. Because this method reads character by character, we need another method that hold these characters in a buffer memory where we can manipulate them, this is the BufferedReader method.
We’ll then use the method ReadLine in the BufferedReader to read text line by line. Modify the class to look as shown:
In the above image, the FileReader needs a file to open so we are passing the name and the path in the variable textpath. The BufferedReader is then provided with the FileReader object and this is handed over between the round brackets.
To read the text, we need an array to store the characters and we also need a loop to go through the text. Add the FOR loop as shown on the image below:
Since we don’t know how many line will be there in any given text, it will be a better programming practice to stop hard-coding the line number (We have hard-coded ours to 3 lines) and write a method that will actually count and return the number of lines in any given text. Add the following readlines() method:
Java program to read a text file
The readlines() method reads and return the number of lines to where it was called from. We’ll call this method to where we want to know the number of lines in the text, so we have replaced this line of code: int textLines = 3; with this one: int textLines = readlines( );
Now, we need to set up a string variable in the main class to hold the name of the text file. Switch back to the main class i.e. TextFiles class and add the following line of code:
Notice that "C:/Myfile/testfile.txt"; refer to a text file in drive C:/ in a folder named Myfile but this file is not there for now so we need to open a text editor like Notepad and create it. Open Notepad, type text of your own but save the file with the name testfile in drive C:/ and in a folder named Myfile.
In the main class, we need to create an object of the ReadFile class. We also need to include the try …catch block to trap Exceptions. Inside the try …catch block we’ll create a loop to go through the lines of text as we output them on console. The final main class (TextFiles class) should look as shown below:
Reading a text file: Main Java class
Run the main class now and you should be able to read text from the text file that we created earlier.
Try to change the name of the text file and attempt to run the program again, this time the Exception handler in the main class should be able to catch the error and alert you that the file you are trying to access does not exist. That is all about reading from a text file in Java. In the next lesson, we shall look at how we can write to a text file in Java programming language.
Other related hubs...
- Programming In Java NetBeans - A Step By Step Tutorial For Beginners: Lesson 1
Java is increasingly becoming the world’s programming language of choice. This tutorial will take you on step by step lessons covering specialized topics on Java programming that are aimed at providing the fundamental skills needed for beginner...
- Programming In Java NetBeans - A Step By Step Tutorial For Beginners: Lesson 2
In this lesson you will learn how to create your first Java project and how to interpret the NetBeans code editor window.
- Programming In Java NetBeans - A Step By Step Tutorial For Beginners: Lesson 5
One of the useful classes that handle inputs from a user in Java is the Scanner class. The Scanner class is located in the util (utility) package of the Java library.
- Programming In Java NetBeans - A Step By Step Tutorial For Beginners: Lesson 11
The WHILE loop in Java execute a statement or a group of statements so long as the specified condition remains TRUE. The loop starts with the keyword “while”. Just after the keyword you open the round brackets and specify the condition to be tested.
Want to make money online?
Previn on November 20, 2013:
Thanks for sharing your excellent knowledge on Java. You are an outstanding online tutor. These tutorials really helped me enhance my basic knowledge on Java.
Danson Wachira (author) from Nairobi, Kenya on March 27, 2013:
Thanks for following the Java lessons tutorial and am glad that the lessons were helpful. More Java lessons coming soon.
Jack Sparrow on March 27, 2013:
Its really very useful for me ..... I completed all the lessons ...nd this gave me confident to do code ..... waiting for the next lessons nd updates
Kim on March 01, 2013:
Very useful Java tutorial, thanks!!
Danson Wachira (author) from Nairobi, Kenya on December 05, 2012:
Thanks for visiting my online tutorials, am glad you found the articles to useful. Let me know if you need more help. Cheers!
Dennis Mathenge from Sweden on December 05, 2012:
It helps alot...I will work with the tutorial lessons no problem. They are very informative. Thanks again for sharing
Danson Wachira (author) from Nairobi, Kenya on November 29, 2012:
I really appreciate you stopping here, reading and commenting. I want to confirm that i received your Email on your request and i was waiting to see what i can do. The lessons contained here in this tutorial are actually written as draft and later fine tuned before publishing. What i have as a backup is a rough copy that might not be of help to you. If you would like to have this tutorial as a pdf, Word file or a zip file it can be done but it will require resources.
I hope this help.
Dennis Mathenge from Sweden on November 29, 2012:
A really following your lessons and grateful since am learning something new. do you have the lessons in a pdf or word format that you can email to me?