Java Reference
In-Depth Information
29
catch (IOException ioException)
30
{
31
System.err.println( "Error opening file. Terminating." );
32
System.exit( 1 );
33
}
34
}
35
36
// read record from file
37
public static void readRecords()
38
{
39
System.out.printf( "%-10s%-12s%-12s%10s%n" , "Account" ,
40
"First Name" , "Last Name" , "Balance" );
41
42
try
43
{
44
while (
input.hasNext()
) // while there is more to read
45
{
46
// display record contents
47
System.out.printf( "%-10d%-12s%-12s%10.2f%n" , input.nextInt(),
input.next(), input.next(), input.nextDouble());
48
49
}
50
}
51
catch (NoSuchElementException elementException)
52
{
53
System.err.println( "File improperly formed. Terminating." );
54
}
55
catch (IllegalStateException stateException)
56
{
57
System.err.println( "Error reading from file. Terminating." );
58
}
59
} // end method readRecords
60
61
// close file and terminate application
62
public static void closeFile()
63
{
64
if (input != null )
65
input.close();
66
}
67
} // end class ReadTextFile
Account First Name Last Name Balance
100 Bob Blue 24.98
200 Steve Green -345.67
300 Pam White 0.00
400 Sam Red -42.16
500 Sue Yellow 224.62
Fig. 15.6 | Sequential file reading using a Scanner . (Part 2 of 2.)
Method openFile (lines 23-34) opens the file for reading by instantiating a Scanner
object in line 27. We pass a Path object to the constructor, which specifies that the
Scanner object will read from the file "clients.txt" located in the directory from which
the application executes. If the file cannot be found, an IOException occurs. The excep-
tion is handled in lines 29-33.
Search WWH ::




Custom Search