Java Streams  «Prev 

More Specific Java Stream Methods

Although InputStream and OutputStream are abstract classes, many methods in the class library are only specified to return an InputStream or OutputStream, not the more-specific subclass.
For example, this is the signature for the openStream() method in

java.net.URL

:

public final InputStream openStream()
 throws IOException

In most implementations of Java, this method actually returns a
sun.net.TelnetInputStream
object, which is a subclass of java.io.InputStream; but you cannot use the methods of that class. Thus you will often only be able to use the methods declared in these base classes.

Opening Channels

Channels serve as conduits to I/O services. I/O falls into two broad categories:
  1. file I/O and
  2. stream I/O.
It is no surprise that there are two types of channels: 1) file and 2) socket.
There is one FileChannel class and three socket channel classes:
  1. SocketChannel,
  2. ServerSocketChannel, and
  3. DatagramChannel.

Channels can be created in several ways. The socket channels have factory methods to create new socket channels directly. But a FileChannel object can be obtained only by calling the getChannel() method on an open RandomAccessFile, FileInputStream, or FileOutputStream object.
You cannot create a FileChannel object directly. File and socket channels are discussed detail in upcoming sections.
SocketChannel sc = SocketChannel.open();
sc.connect (new InetSocketAddress ("somehost", someport));
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.socket().bind (new InetSocketAddress (somelocalport));
DatagramChannel dc = DatagramChannel.open();
RandomAccessFile raf = new RandomAccessFile ("somefile", "r");
FileChannel fc = raf.getChannel();

The socket classes of java.net have new getChannel() methods as well. While these methods return a corresponding socket channel object, they are not sources of new channels as RandomAccessFile.getChannel() is. They return the channel associated with a socket if one already exists; they never create new channels.