Java Reference
In-Depth Information
Use the
Scanner
class for reading text data from a file and the
PrintWriter
class
for writing text data to a file.
Key
Point
A
File
object encapsulates the properties of a file or a path, but it does not contain the meth-
ods for creating a file or for writing/reading data to/from a file (referred to as data
input
and
output
, or
I/O
for short). In order to perform I/O, you need to create objects using appropri-
ate Java I/O classes. The objects contain the methods for reading/writing data from/to a file.
There are two types of files: text and binary. Text files are essentially characters on disk. This
section introduces how to read/write strings and numeric values from/to a text file using the
Scanner
and
PrintWriter
classes. Binary files will be introduced in Chapter 17.
VideoNote
Write and read data
12.11.1 Writing Data Using
PrintWriter
The
java.io.PrintWriter
class can be used to create a file and write data to a text file.
First, you have to create a
PrintWriter
object for a text file as follows:
PrintWriter output =
new
PrintWriter(filename);
Then, you can invoke the
print
,
println
, and
printf
methods on the
PrintWriter
object
to write data to a file. Figure 12.8 summarizes frequently used methods in
PrintWriter
.
java.io.PrintWriter
+PrintWriter(file: File)
Creates a
PrintWriter
object for the specified file object.
+PrintWriter(filename: String)
+print(s: String): void
Creates a
PrintWriter
object for the specified file-name string.
Writes a string to the file.
+print(c: char): void
+print(cArray: char[]): void
+print(i: int): void
+print(l: long): void
+print(f: float): void
+print(d: double): void
+print(b: boolean): void
Also contains the overloaded
println
methods.
Writes a character to the file.
Writes an array of characters to the file.
Writes an
int
value to the file.
Writes a
long
value to the file.
Writes a
float
value to the file.
Writes a
double
value to the file.
Writes a
boolean
value to the file.
A
println
method acts like a
print
method; additionally, it
prints a line separator. The line-separator string is defined
by the system. It is
\r\n
on Windows and
\n
on Unix.
The
printf
method was introduced in §4.6, “Formatting
Console Output.”
Also contains the overloaded
printf
methods.
F
IGURE
12.8
The
PrintWriter
class contains the methods for writing data to a text file.
Listing 12.13 gives an example that creates an instance of
PrintWriter
and writes two
lines to the file
scores.txt
. Each line consists of a first name (a string), a middle-name initial
(a character), a last name (a string), and a score (an integer).
L
ISTING
12.13
WriteData.java
1
public class
WriteData {
2
public static void
main(String[] args)
throws
IOException {
3 java.io.File file =
new
java.io.File(
"scores.txt"
);
4
if
(file.exists()) {
5 System.out.println(
"File already exists"
);
6 System.exit(
1
);
7
throws an exception
create
File
object
file exist?
}
8
Search WWH ::
Custom Search