Java

TOPIC I01 – READING FROM A FILE

 

 

LESSON NOTE

 

 

INTRO

 

As long as you set your code up correctly, reading from a file is quite easy.  In fact, all the work you will have to do will be quite similar.

 

CREATING A FILE TO READ FROM

 

In Eclipse, it is best to place your file in your project folder (but not in your src folder).  To create such a file, simply right click on the project name’s, choose New > File and name the file something like data.txt. 

 

 

STEPS TO READING FROM A FILE

 

These are the steps that you would use in any language:

 

Step 1 – Open the file.

 

This sounds easy.  Unfortunately, opening a file requires a fair bit of knowledge.   Fortunately, most languages come with functions or classes that do this for you!  So this step is very easy.

 

Step 2 – Read the data.

 

You will read the data one line at a time.  This occurs inside a simple loop that continues until the end of the file is reached.

 

Step 3 – Close the file.

 

You simply release the file.  This is important so that Windows knows that you are done using the file.  Forgetting to do this is an error (even if Java doesn’t complain).

EXAMPLE PROGRAM

 

 

TEXT FILE WITH CODE

 

Click here to get the code in a text file.

 

THINGS TO CHANGE FOR YOUR PROGRAM

 

When you want to create your program, here is what you have to change:

 

  • You need to change the file name to whatever your file name is.  In the example, it is “testme.txt”.
  • You need to change the code inside the while loop to do whatever you want to do with each line.

 

EXAMPLE

 

Write the program needed to count the number of lines in a file.  Only show the loop section of the code (because nothing else is different from the template above).

 

Solution

 

      //2-READ DATA

      //Data is read one line at a time.

     

      String line = in.readLine();

      int count = 0;

     

      while(line != null)

      {

         count = count + 1;

        

         //UPDATE line to NEXT LINE

        

         line = in.readLine();

      }

  

      //The variable count now holds the number of lines.

 

System.out.println("Number of lines: " + count);