Java All-in-One For Dummies
Book image
Explore Book Buy On Amazon

In Java, like in almost any computer programming language, reading data from a file can be tricky. You add extra lines of code to tell the computer what to do. Sometimes you can copy and paste these lines from other peoples’ code.

import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class DoPayroll {
    public static void main(String args[])
                                  throws IOException {
        Scanner diskScanner =
            new Scanner(new File("EmployeeInfo.txt"));
        for (int empNum = 1; empNum <= 3; empNum++) {
            payOneEmployee(diskScanner);
        }
        diskScanner.close();
    }
    static void payOneEmployee(Scanner aScanner) {
        Employee anEmployee = new Employee();
        anEmployee.setName(aScanner.nextLine());
        anEmployee.setJobTitle(aScanner.nextLine());
        anEmployee.cutCheck(aScanner.nextDouble());
        aScanner.nextLine();
    }
}

For example, you can follow the pattern in this listing:

/*
 * The pattern in Listing 8-2
 */
import java.util.Scanner;
<b>import java.io.File;</b>
<b>import java.io.IOException;</b>
class <i>SomeClassName</i> {
    public static void main(String args[]) 
                                  <b>throws IOException</b> {
        Scanner <b><i>scannerName</i></b> =
            new Scanner(<b>new File("</b><b><i>SomeFileName</i></b><b>"</b>));
        //<i>Some code goes here</i>
        <b><i>scannerName</i></b>.nextInt();
        <b><i>scannerName</i></b>.nextDouble();
        <b><i>scannerName</i></b>.next();
        <b><i>scannerName</i></b>.nextLine();
        //<i>Some code goes here</i>
        <b><i>scannerName</i></b>.close();
    }
}

You want to read data from a file. You start by imagining that you’re reading from the keyboard. Put the usual Scanner and next codes into your program. Then add some extra items from the listing pattern:

  • Add two new import declarations — one for java.io.File and another for java.io.IOException.

  • Type throws IOException in your method’s header.

  • Type new File(") in your call to new Scanner.

  • Take a file that’s already on your hard drive. Type that filename inside the quotation marks.

  • Take the word that you use for the name of your scanner. Reuse that word in calls to next, nextInt, nextDouble, and so on.

  • Take the word that you use for the name of your scanner. Reuse that word in a call to close.

Occasionally, copying and pasting code can get you into trouble. Maybe you’re writing a program that doesn’t fit the simple listing pattern. You need to tweak the pattern a bit. But to tweak the pattern, you need to understand some of the ideas behind the pattern.

About This Article

This article can be found in the category: