Have you ever wanted to know how to read content from a text file using Java, but you were to embarrassed to ask?

Follow these steps pilgrim (I’m assuming your using an IDE like NetBeans or Eclipse…):

  1. Create a new project folder.
  2. Create a package, call it readfromfile (all lowercase please).
  3. Create a new class file
    • name it ReadMain,
    • check the option to make it the main class.
  4. Create a new class, name it ReadFile.
  5. Create a text file in notepad
    • copy and paste some text into it, anything will do…
    • save the file as source.txt
Okay, that’s your setup complete, moving on…

In the ReadFile, copy and paste the following:

package readfromfile;

import java.util.Scanner;
import java.io.File;

public class ReadFile {
       private Scanner scan;

public ReadFile(){

}

//create method to read from text file
public void openFile(String fulltext){
     try{
        scan = new Scanner(new File(fulltext));
    }
   catch (Exception e){
       System.out.println(“Failed to read file”);
   }
}

//read the content of the file and count the words
public void readCount(){
     int count = 0;
     while(scan.hasNext()){
          String wordNum = scan.next();
          count++;
     }System.out.println(“Number of words in file: ” + count);
}

}

In the main class (the other file you created), copy and paste the following:

package readfromfile;

public class ReadMain {

        public static void main(String[] args) {
               ReadFile read = new ReadFile();
               read.openFile(“source.txt”);
               read.readCount();
        }
}

Hit the run button (agree to save if you’re given the option).

Method To The Madness…

A couple of points to clarify. The import statements are required, without them the Scanner and File objects will not have access to the Java classes they need to work.

The first method uses a String argument that will be passed to it in the main class. This will be the “source.txt” file you created in notepad, and the method will access the content in that text file.

You may have used Scanner before to take input from the user via the keyboard. If that was the case you would have used(System.in), but in this case we can use (new File(fulltext)); fulltext being the argument you pass to the method, i.e. “source.txt”.

The Scanner code in this method is contained in a try block, followed by a catch block. This will return an error “Failed to read file” if the “source.txt” file is not in the correct folder. The benefit to try, catch exception handling is it can tell you which method is producing the error. You can imagine how useful that would be in code with more classes and methods.

There’s More Than One Method…

On to the second method. This one we’re going to use to read the content of the text file and count the words therein.

We start by declaring an int count variable, we’ll need this to count the number of words in the text file. This variable’s scope is local to the method. It is used within the following while loop, but we will need to access it for print output outside of that while loop. Therefore it must be declared outside of the loop.

The while loop is a nice little piece of code. It says while ‘scan’ (our Scanner object reading the text file) has not reach the end of the file content, then keep on doing whatever follows. The next line

String wordNum = scan.next();

declares a String to hold each word. Those words are copied from the text file with the .next() method, which goes to the next word in the file. Because we’re in a while loop, this process of assigning each word in turn to the String reference continues until we read the end of the file. Nice. (Of course the String’s initial value does not change, cos’ it’s immutable, but that’s another story…).

While this goes on, our innocent looking ‘count’ variable is incrementing it’s value with every new word found in the text file. When the last word is finally counted, and all conditions have all been met, we pop out of the loop into the waiting arms of the System.out.println.

But wait, we’re not finished just yet. That println statement will never see the light of day unless those handy little methods are called in the main class. Time to bring this baby home.

The Main Class Will Not Be Ignored

Go to your file titled ReadMain (this is your main class). Create a new instance of the class with your methods in it with:

ReadFile read = new ReadFile();

Whenever you use the ReadFile methods in the main class, you will use ‘read.‘ to let your programme know that’s the class you are calling the method from. That’s exactly what we do in the two lines of code that follow.

read.openFile(“source.txt”);

This method must be included, or you won’t be able to read/access the text file. See how we refer to it with read.? If you’re feeling brave leave read. out of that line of code and see what happens, I dare ya’. Do you remember that String argument parameter we included in the method? That’s what we used to call the “source.txt” file into our method. We could use that method to call any text file content. I don’t know about you but that’s pretty exciting stuff to me.

Next we call the readCount() method. This executes the processes with the method and gives us our word count output. Cool!

Conclusion…

  • So you have created a class with two methods, one to open a File with a Scanner, the other to loop through the file and count the words in it.
  • Then you called an instance of that class in your main class, where you called your methods, passed a text file to one, and enjoyed the print output of the word count from the other.
  • This of course is just the start of what you can do with a text file in Java. I hope it helped fellow Java newbies to better understand how to read from a file and extract information from it.
Challenges
  1. Find and extract the first word from your text file.
  2. Find and extract the first sentence from your text file.
  3. Return a String, with all the content of your text file, except the first sentence should be removed.
  • Hint keywords: substring, indexOf, length.