AP Computer Science Java: Lesson 4.1
Working with Text - Text Files


Lesson 4.1 - Working with Text Files
Purpose: To learn how to read data from text variables using EasyReader

File In, Please  
Until now, all of our input has come via the keyboard. We have performed input with an EasyReader input variable. The default input object is the keyboard. But we can also get input from a text file. Here is an example that reads integer values from a file and displays them on the screen:

public class ReadFile
{
    public static void
main(String[] args)
    {
        EasyReader inFile = new EasyReader("data.txt");
        int
number;
        number = inFile.readInt();
        while
(!inFile.eof())
        {
            System.out.print(number + " ");
            number = inFile.readInt();
        }
    }
}

Note that a while loop is used to determine when the file is out of data. The eof stands for "end of file," so the condition says "while we have not reached the end of the file," continue reading data.

In closing, declaring an input file variable is just like declaring a keyboard variable. The only difference is the need to specify a file path in the parentheses after the second EasyReader. Be sure to verify that the file path is valid.

© DanShuster.com