23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

The compiler rewrites this complicated expression as:<br />

StringBuffer sb = new StringBuffer();<br />

sb.append("As of ");<br />

Date d = new Date();<br />

sb.append(d);<br />

sb.append(" there have been over ");<br />

sb.append(hits);<br />

sb.append(" hits on the web site.")<br />

String s = sb.toString();<br />

System.out.println(s);<br />

<strong>Java</strong> I/O<br />

The StringBuffer append() method is overloaded in much the same way that the print()<br />

and println() methods are so it can handle any <strong>Java</strong> data type.<br />

PrintStream methods never throw <strong>IO</strong>Exceptions. Each method in the class catches<br />

<strong>IO</strong>Exceptions. When an exception occurs, an internal flag is set to true. You test this flag<br />

with the checkError() method:<br />

public boolean checkError()<br />

This method returns true if this print stream has ever encountered an error during its lifetime.<br />

Most of the time, you just ignore this, since print streams are only used in situations where<br />

exhaustive error checking is unnecessary.<br />

Besides System.out and System.err, you can create new print streams with these<br />

constructors:<br />

public PrintStream(OutputStream out)<br />

public PrintStream(OutputStream out, boolean autoFlush)<br />

The out argument is just the underlying output stream. The autoFlush argument is a<br />

boolean (true or false). If it's true, then the stream is flushed every time a linefeed (\n)<br />

character or byte is written, a println()method is invoked, or a byte array is written.<br />

The biggest problem with the PrintStream class is that it does not properly handle<br />

international character sets. In Chapter 15 you'll learn about the PrintWriter class that has<br />

much of the same functionality but can handle international character sets.<br />

6.6 Multitarget Output Streams<br />

As a final example, I present two slightly unusual filter output streams that direct their data to<br />

multiple underlying streams. The TeeOutputStream class, given in Example 6.5, has not one<br />

but two underlying streams. The TeeOutputStream does not modify the data that's written in<br />

any way; it merely writes it on both of its underlying streams.<br />

Example 6.5. The TeeOutputStream Class<br />

package com.macfaq.io;<br />

import java.io.*;<br />

85

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!