ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

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

Updated on October 23, 2019
dwachira profile image

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; 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

package textfiles;


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();
    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){
       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:

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

package textfiles;
public class TextFiles {

  public static void main(String[] args)throws IOException{
        String file_name = "C:/Myfile/testfile.txt";
            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.

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 >>


    0 of 8192 characters used
    Post Comment
    • profile image


      6 years ago

      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!

    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

      Hi Jack,

      Thanks for following the Java lessons tutorial and am glad that the lessons were helpful. More Java lessons coming soon.

    • profile image

      Jack Sparrow 

      7 years ago

      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

    • profile image


      7 years ago

      Very useful Java tutorial, thanks!!

    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

      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!

    • denism profile image

      Dennis Mathenge 

      7 years ago from Sweden

      It helps alot...I will work with the tutorial lessons no problem. They are very informative. Thanks again for sharing

    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

      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.

    • denism profile image

      Dennis Mathenge 

      7 years ago from Sweden

      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?


    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at:

    Show Details
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the or domains, for performance and efficiency reasons. (Privacy Policy)
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)