Java Reference
In-Depth Information
Display 2.12
Program to Read the Text File in Display 2.11
1
import
java.util.Scanner;
2
import
java.io.FileInputStream;
3
import
java.io.FileNotFoundException;
4
5
public class
TextFileDemo
6 {
7
public static void
main(String[] args)
8 {
9 Scanner fileIn =
null
;
// Initializes fileIn to empty
10
try
11 {
12
// Attempt to open the file
13 fileIn =
new
Scanner(
14
new
FileInputStream("player.txt"));
15 }
16
catch
(FileNotFoundException e)
17 {
18
// This block executed if the file is not found
19
// and then the program exits
20 System.out.println("File not found.");
21 System.exit(0);
22 }
23
24
// If the program gets here then
25
// the file was opened successfully
26
int
highscore;
27 String name;
28
29 System.out.println("Text left to read? " +
30 fileIn.hasNextLine());
31 highscore = fileIn.nextInt();
32 fileIn.nextLine();
// Read newline left from nextInt()
33 name = fileIn.nextLine();
34
35 System.out.println("Name: " + name);
36 System.out.println("High score: " + highscore);
37 System.out.println("Text left to read? " +
38 fileIn.hasNextLine());
39 fileIn.close();
40 }
41 }
Sample Dialogue
try and catch
is
explained in more
detail in Chapter 9.
The file
player.
txt
should be in the
same directory as
the Java program.
You can also supply
a full pathname
to the file.
This line is
explained earlier
in this chapter in the
Pitfall section “Dealing with
the Line Terminator
'\n'
”
Text left to read? true
Name: Gordon Freeman
High score: 100510
Text left to read? False