Java Reference
In-Depth Information
System.out.println("File not found.");
System.exit(0);
}
... Code continues here
This code will create a Scanner variable named fileIn and initialize it to an empty
( null ) object. Next, Java will run the code inside the try block. If the file is not found,
then control jumps directly to the catch block. In our example, we print out an error
message and make the program exit immediately with the statement System.exit(0) .
If the file is found, then the catch block is skipped entirely and the program
continues to execute whatever code comes after the catch. At this point, we can use
fileIn exactly the same way we used a Scanner object connected to the console,
except input will be provided from the file, not the keyboard.
For example, we can use fileIn.nextInt() to read an integer from the file, fileIn.
nextDouble() to read a double from the file, fileIn.next() to read a string token
from the file, or fileIn.nextLine() to read an entire line from the text file. Java begins
reading from the beginning of the file and proceeds toward the end as data is read.
Unlike reading from the console, we might want to know if we have reached the end
of the file. We can use fileIn.hasNextLine() to determine if there is data to read.
When we are done with the file, we can close it with fileIn.close(), which will
release any resources that have been allocated by Java in association with the file.
A complete example is shown in Displays 2.11 and 2.12 . Display 2.11 shows the
contents of a text file named player.txt . This file can be created by any program
that saves in the plain text format. As an example, let's say that the file contains
information about the last player to play a game. The first line of the file contains the
high score of the player, 100510, and the second line contains the name of the player,
Gordon Freeman. The program in Display 2.12 reads in this information and displays
it. It reads in the high score using nextInt() and then reads in the name using
nextLine() . Note that we have to use an additional nextLine() after the nextInt()
to deal with the newline character for the exact same reason discussed earlier in this
chapter in the Pitfall in Section 2.2 titled Dealing with the Line Terminator, '\n'.
Display 2.11
Sample Text File, player.txt, to Store a Player's High Score and Name
100510
Gordon Freeman
 
Search WWH ::




Custom Search