These allow a PrintWriter to be created from a File object 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, the PrintWriter object directs all output to the specified file. You
can specify a character encoding by passing its name in charSet.
PrintWriter supports the print( ) and println( ) methods for all types, including Object.
If an argument is not a primitive type, the PrintWriter methods will call the object's toString( )
method and then output the result.
PrintWriter also supports the printf( ) method. It works the same way it does in the
PrintStream class described earlier: it allows you to specify the precise format of the data.
Here is how printf( ) is declared in PrintWriter:
PrintWriter printf(String fmtString, Object ... args)
PrintWriter printf(Locale loc, String fmtString, Object ... args)
The first version writes args to standard output in the format specified by fmtString, using the
default locale. The second lets you specify a locale. Both return the invoking PrintWriter.
The format( ) method is also supported. It has these general forms:
PrintWriter format(String fmtString, Object ... args)
PrintWriter format(Locale loc, String fmtString, Object ... args)
It works exactly like printf( ).
The Console Class
Java SE 6 adds the Console class. It is used to read from and write to the console, if one exists.
It implements the Flushable interface. Console is primarily a convenience class because most
of its functionality is available through System.in and System.out. However, its use can
simplify some types of console interactions, especially when reading strings from the console.
Console supplies no constructors. Instead, a Console object 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, null is returned. A
console will not be available in all cases. Thus, if null is returned, no console I/O is possible.
Console defines the methods shown in Table 19-5. Notice that the input methods, such as
readLine( ), throw IOError if an input error occurs. IOError is a new exception added by Java
SE 6, and it is a subclass of Error. It indicates an I/O failure that is beyond the control of your
program. Thus, you will not normally catch an IOError. Frankly, if an IOError is thrown while
accessing the console, it usually means that there has been a catastrophic system failure.
Also notice the readPassword( ) 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.
Search WWH :