Updated date:

Programming in Java Netbeans - A Step by Step Tutorial for Beginners: Lesson 34

Danson Wachira is a certified Trainer in Computer Science, Information Technology and related studies.

Table of Contents

<< Lesson 33 | Lesson 35 >>

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.

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-34

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:

import java.io.IOException;

The main class should be able to trap errors so the class should look as shown below with the added statement to trap Exceptions:

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-34

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:

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-34

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:

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-34

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:

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-34

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:

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-34

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

package textfiles;

import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;

public class ReadFile {
    private String textpath;
    
    public ReadFile(String file_path){
        textpath = file_path;
    }
    
    public String[] OpenFile() throws IOException{
       FileReader fr = new FileReader(textpath);
       BufferedReader textReader = new BufferedReader(fr);
       
        int textLines = readlines();
        String[] textData = new String[textLines];
        int i;
        for (i=0; i < textLines; i++) {
        textData[i] = textReader.readLine();
        }
        textReader.close();
    return textData;
 }
      
   int readlines() throws IOException{
       FileReader read_file = new FileReader(textpath);
       BufferedReader bfile = new BufferedReader(read_file);
       String aLine;
       int numLines = 0;
       
       while((aLine = bfile.readLine()) != null){
           numLines++;
       }
       bfile.close();
       return numLines;
   }
}

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:

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-34

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.

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-34

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

package textfiles;
import java.io.IOException;
public class TextFiles {

  public static void main(String[] args)throws IOException{
        String file_name = "C:/Myfile/testfile.txt";
        
        try{
            ReadFile file = new ReadFile(file_name);
            String[ ] aryLines = file.OpenFile();
            
            int i;
            for ( i=0; i < aryLines.length; i++ ) {
            System.out.println(aryLines[i]) ;
            }

        }catch ( IOException e ) {
        System.out.println( e.getMessage() );
      }
    }
}

Run the main class now and you should be able to read text from the text file that we created earlier.

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-34

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.

<< Lesson 33 | Lesson 35 >>

Other related hubs...

Want to make money online?

Comments

Previn on November 20, 2013:

Hi Dwachira

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.

Thank You

God bless!

Danson Wachira (author) from Nairobi, Kenya on March 27, 2013:

Hi Jack,

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:

Hi denism,

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:

Hi denism,

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?

Related Articles