Java Reference
In-Depth Information
in UTF-8 or UTF-16 unless the server tells it otherwise. However, a web server that uses
PrintStream may well send the files encoded in CP1252 from a U.S.-localized Windows
system or SJIS from a Japanese-localized system, whether the client expects or under‐
stands those encodings or not. PrintStream doesn't provide any mechanism for chang‐
ing the default encoding. This problem can be patched over by using the related Print
Writer class instead. But the problems continue.
The third problem is that PrintStream eats all exceptions. This makes PrintStream
suitable for textbook programs such as HelloWorld, because simple console output can
be taught without burdening students with first learning about exception handling and
all that implies. However, network connections are much less reliable than the console.
Connections routinely fail because of network congestion, phone company misfea‐
sance, remote systems crashing, and many other reasons. Network programs must be
prepared to deal with unexpected interruptions in the flow of data. The way to do this
is by handling exceptions. However, PrintStream catches any exceptions thrown by the
underlying output stream. Notice that the declaration of the standard five Output
Stream methods in PrintStream does not have the usual throws IOException decla‐
ration:
public abstract void write ( int b )
public void write ( byte [] data )
public void write ( byte [] data , int offset , int length )
public void flush ()
public void close ()
Instead, PrintStream relies on an outdated and inadequate error flag. If the underlying
stream throws an exception, this internal error flag is set. The programmer is relied
upon to check the value of the flag using the checkError() method:
public boolean checkError ()
To do any error checking at all on a PrintStream , the code must explicitly check every
call. Furthermore, once an error has occurred, there is no way to unset the flag so further
errors can be detected. Nor is any additional information available about the error. In
short, the error notification provided by PrintStream is wholly inadequate for unreli‐
able network connections.
Data Streams
The DataInputStream and DataOutputStream classes provide methods for reading and
writing Java's primitive data types and strings in a binary format. The binary formats
used are primarily intended for exchanging data between two different Java programs
through a network connection, a datafile, a pipe, or some other intermediary. What a
data output stream writes, a data input stream can read. However, it happens that the
formats are the same ones used for most Internet protocols that exchange binary num‐
bers. For instance, the time protocol uses 32-bit big-endian integers, just like Java's int
Search WWH ::




Custom Search