Reading from Text Files

If we want to read information from a text file into a program, we first need to open a connection to the file. We do this by creating a Scanner (like we do to get user input). This time, however, we’ll connect the Scanner to a file:

Scanner s = new Scanner(new File(filename));

Here, filename is a string that is the name of the input file. This file should be stored in the same directory as the class that’s using it. Alternatively, you can specify the absolute path of the file (e.g., “C:\Documents and Settings...”). To read a single line in the file, do this:

String line = s.nextLine();

The first line of the file will be stored in the line variable. If we call nextLine() again, it will read the second line, and so on. To see if you’ve reached the end of the input file, use the hasNext() command. This will return false if we’re at the end of the file, and true otherwise. When you’re done reading from a file, you need to close it:

s.close();

Here’s an example that opens the file “in.txt” and prints every line from the file to the screen:

Scanner s = new Scanner(new File("in.txt"));
while (s.hasNext()) 
{
    String line = s.nextLine();
    System.out.println(line);
}
s.close();

If in.txt looked like this:

Hi
Testing
example

Then our program would print to the terminal:

Hi
Testing
example

You will often read files that have a bunch of information on each line – say, a bunch of names separated by spaces. To process each name, read each line (as shown above), and then use a StringTokenizer to break apart each line.