Java Reference
In-Depth Information
11. FileWriter fw = new FileWriter(“characters.txt”);
12. PrintWriter out = new PrintWriter(fw);
13. out.print(i);
14. out.println(d);
15. out.println(s);
16. out.println(b);
17. out.close();
18. fw.close();
The new
FileWriter
on line 11 creates a fi le named
characters.txt
, which is chained
to a
PrintWriter
on line 12. Line 13 prints
i
without an ending line feed, so
d
gets printed
on the same line as
i
. The
StringBuilder s
and the
boolean b
are printed next on their
own lines, and the resulting fi le looks like this:
1010.3333333333333333
hello
true
The
int
,
double
, and
boolean
are converted to characters and output to the fi le. The
value of
d
prints a long list of
3
s because it is the fraction one third. The
print
and
println
methods cannot be used to control the format of
d
. If you need control over formatting, use
the
format
method of
PrintWriter
, which is discussed next.
The
format and printf
Methods
The
format
method of a
PrintWriter
object writes a formatted string to the stream using
a specifi ed format string and arguments. Along with general knowledge of the
PrintWriter
class, the exam objectives specifi cally state that you need to be able to “write code using
PrintWriter.format/printf
methods.” In addition, you must be able to “recognize and
use formatting parameters (limited to:
%b
,
%c
,
%d
,
%f
,
%s
) in format strings.” The
Print-
Writer
class has been a part of the Java language since JDK 1.1, but the
format
and
printf
methods were introduced in Java 5.0.
As a convenience to C programmers familiar with C's
printf
function,
PrintWriter
also contains a
printf
method. The signatures of the two methods are
public PrintWriter format(String fmt, Object... args)
public PrintWriter printf(String fmt, Object... args)
Aside from their names, there is no difference between the
format
and
printf
methods.
Their output and behavior is identical. The return value of both is the
PrintWriter
object,
which allows for chaining of method calls. The
fmt
parameter consists of fi xed text and one
Search WWH ::
Custom Search