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
Opening Channels
Channels serve as conduits to I/O services. I/O falls into two broad categories:
- file I/O and
- 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:
- SocketChannel,
- ServerSocketChannel, and
- 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.