Java Reference
In-Depth Information
as web servers. Normally, the basic stream model is all you need and all you should use
for clients. Because channels and buffers depend on streams, I'll start with streams and
clients and later discuss nonblocking I/O for use with servers in Chapter 11 .
Output Streams
Java's basic output class is java.io.OutputStream :
public abstract class OutputStream
This class provides the fundamental methods needed to write data. These are:
public abstract void write ( int b ) throws IOException
public void write ( byte [] data ) throws IOException
public void write ( byte [] data , int offset , int length )
throws IOException
public void flush () throws IOException
public void close () throws IOException
Subclasses of OutputStream use these methods to write data onto particular media. For
instance, a FileOutputStream uses these methods to write data into a file. A
TelnetOutputStream uses these methods to write data onto a network connection. A
ByteArrayOutputStream uses these methods to write data into an expandable byte array.
But whichever medium you're writing to, you mostly use only these same five methods.
Sometimes you may not even know exactly what kind of stream you're writing onto.
For instance, you won't find TelnetOutputStream in the Java class library documenta‐
tion. It's deliberately hidden inside the sun packages. It's returned by various methods
in various classes in java.net , like the getOutputStream() method of java.net.Sock
et . However, these methods are declared to return only OutputStream , not the more
specific subclass TelnetOutputStream . That's the power of polymorphism. If you know
how to use the superclass, you know how to use all the subclasses, too.
OutputStream 's fundamental method is write(int b) . This method takes an integer
from 0 to 255 as an argument and writes the corresponding byte to the output stream.
This method is declared abstract because subclasses need to change it to handle their
particular medium. For instance, a ByteArrayOutputStream can implement this meth‐
od with pure Java code that copies the byte into its array. However, a FileOutput
Stream will need to use native code that understands how to write data in files on the
host platform.
Take note that although this method takes an int as an argument, it actually writes an
unsigned byte. Java doesn't have an unsigned byte data type, so an int has to be used
here instead. The only real difference between an unsigned byte and a signed byte is the
interpretation. They're both made up of eight bits, and when you write an int onto a
network connection using write(int b) , only eight bits are placed on the wire. If an
int outside the range 0-255 is passed to write(int b) , the least significant byte of the
Search WWH ::




Custom Search