Chapter 19: Input/Output: Exploring java.io 587
These allow aPrintWriterto be created from aFileobject or by specifying the name of a file.
In either case, the file is automatically created. Any preexisting file by the same name is
destroyed. Once created, thePrintWriterobject directs all output to the specified file. You
can specify a character encoding by passing its name incharSet.
PrintWritersupports theprint( )andprintln( )methods for all types, includingObject.
If an argument is not a primitive type, thePrintWritermethods will call the object’stoString( )
method and then output the result.
PrintWriteralso supports theprintf( )method. It works the same way it does in the
PrintStreamclass described earlier: it allows you to specify the precise format of the data.
Here is howprintf( )is declared inPrintWriter:
PrintWriter printf(StringfmtString, Object ...args)
PrintWriter printf(Localeloc, StringfmtString, Object ...args)
The first version writesargsto standard output in the format specified byfmtString,using the
default locale. The second lets you specify a locale. Both return the invokingPrintWriter.
Theformat( )method is also supported. It has these general forms:
PrintWriter format(StringfmtString, Object ...args)
PrintWriter format(Localeloc, StringfmtString, Object ...args)
It works exactly likeprintf( ).
The Console Class
Java SE 6 adds theConsoleclass. It is used to read from and write to the console, if one exists.
It implements theFlushableinterface.Consoleis primarily a convenience class because most
of its functionality is available throughSystem.inandSystem.out. However, its use can
simplify some types of console interactions, especially when reading strings from the console.
Consolesupplies no constructors. Instead, aConsoleobject is obtained by calling
System.console( ), which is shown here:
static Console console( )
If a console is available, then a reference to it is returned. Otherwise,nullis returned. A
console will not be available in all cases. Thus, ifnullis returned, no console I/O is possible.
Consoledefines the methods shown in Table 19-5. Notice that the input methods, such as
readLine( ), throwIOErrorif an input error occurs.IOErroris a new exception added by Java
SE 6, and it is a subclass ofError. It indicates an I/O failure that is beyond the control of your
program. Thus, you will not normally catch anIOError. Frankly, if anIOErroris thrown while
accessing the console, it usually means that there has been a catastrophic system failure.
Also notice thereadPassword( )methods. These methods let your application read a
password without echoing what is typed. When reading passwords, you should “zero-out”
both the array that holds the string entered by the user and the array that holds the password
that the string is tested against. This reduces the chance that a malicious program will be able
to obtain a password by scanning memory.