Page 644 - Introduction to Programming with Java: A Problem Solving Approach
P. 644
610 Chapter 15 Files
Figure 15.5 contains a ReadTextFile program that can read the data in either of those files. Be aware that the numbers appearing in Figure 15.4b do not go into the program as numbers. They go into the pro- gram as string representations of numbers. The ReadTextFile program prompts the user for a filename (such as markAntony.txt or randomNumbers.txt), reads the specified file, and prints the file’s contents. Most of the program’s code is straightforward, but some of it deserves attention. . . .
You’ve used the Scanner class for keyboard input for quite a while now. When using the Scanner class for file input, you can still use your old friends, nextInt, nextDouble, nextLine, and so on the same way that you did for keyboard input. But with file input, you should be aware of several addi- tional Scanner methods. When you’re done reading from the Scanner file, call its close method. See fileIn.close() in Figure 15.5. Also, when reading a series of lines from a file, you’ll often want to use Scanner’s hasNextLine method in a while loop header, as we do in Figure 15.5.
/**************************************************************
*
ReadTextFile.java
Dean & Dean
This reads data from a text file.
**************************************************************/
*
*
*
import java.util.Scanner;
import java.io.*;
public class ReadTextFile
{
public static void main(String[] args)
{
Apago PDF Enhancer
Scanner stdIn = new Scanner(System.in);
Scanner fileIn;
String line;
try
{
Open the file.
System.out.print("Enter filename: ");
fileIn = new Scanner(new FileReader(stdIn.nextLine()));
while (fileIn.hasNextLine())
{
}
line = fileIn.nextLine();⎫ System.out.println(line);⎬⎭
}
// end ReadTextFile class
}
// end main
}
fileIn.close();
Close the file.
catch (FileNotFoundException e)
{
}
System.out.println("Error: " + e.getMessage());
Read a line from the file and print it.
Figure 15.5 ReadTextFile program that reads text from the keyboard and also from a text file