Java Reference
In-Depth Information
A resource is declared and created followed by the keyword
try
. Note that the resources are
enclosed in the parentheses (lines 9-12). The resources must be a subtype of
AutoCloseable
such as a
PrinterWriter
that has the
close()
method. A resource must be declared and
created in the same statement and multiple resources can be declared and created inside the
parentheses. The statements in the block (lines 12-18) immediately following the resource
declaration use the resource. After the block is finished, the resource's
close()
method
is automatically invoked to close the resource. Using try-with-resources can not only avoid
errors but also make the code simpler.
12.11.3 Reading Data Using
Scanner
The
java.util.Scanner
class was used to read strings and primitive values from the con-
sole in Section 2.3, Reading Input from the Console. A
Scanner
breaks its input into tokens
delimited by whitespace characters. To read from the keyboard, you create a
Scanner
for
System.in
, as follows:
Scanner input =
new
Scanner(System.in);
To read from a file, create a
Scanner
for a file, as follows:
Scanner input =
new
Scanner(
new
File(filename));
Figure 12.9 summarizes frequently used methods in
Scanner
.
java.util.Scanner
+Scanner(source: File)
+Scanner(source: String)
+close()
+hasNext(): boolean
+next(): String
+nextLine(): String
+nextByte(): byte
+nextShort(): short
+nextInt(): int
+nextLong(): long
+nextFloat(): float
+nextDouble(): double
+useDelimiter(pattern: String):
Scanner
Creates a
Scanner
that scans tokens from the specified file.
Creates a
Scanner
that scans tokens from the specified string.
Closes this scanner.
Returns true if this scanner has more data to be read.
Returns next token as a string from this scanner.
Returns a line ending with the line separator from this scanner.
Returns next token as a
byte
from this scanner.
Returns next token as a
short
from this scanner.
Returns next token as an
int
from this scanner.
Returns next token as a
long
from this scanner.
Returns next token as a
float
from this scanner.
Returns next token as a
double
from this scanner.
Sets this scanner's delimiting pattern and returns this scanner.
F
IGURE
12.9
The
Scanner
class contains the methods for scanning data.
Listing 12.15 gives an example that creates an instance of
Scanner
and reads data from
the file
scores.txt
.
L
ISTING
12.15
ReadData.java
1
import
java.util.Scanner;
2
3
public class
ReadData {
4
public static void
main(String[] args)
throws
Exception {
5
// Create a File instance
6 java.io.File file =
new
java.io.File(
"scores.txt"
);
7
8
// Create a Scanner for the file
9 Scanner input =
new
Scanner(file);
create a
File
create a
Scanner
Search WWH ::
Custom Search