Java Streams  «Prev  Next»

Lesson 6 Java Stream Classes
ObjectiveFamiliarize yourself with the stream classes in the java.io package.

Java Stream Classes

Most classes that work directly with streams are part of the java.io package. There are also a few streams classes in java.util.zip.
Question: What is a stream? Is 1) data, 2) data source, or 3) data destination?
Answer: A stream is a sequence of data.
The Java I/O stream is an abstraction of a data source or a data destination and represents an object that can produce data or receive data.
An input stream is used to read data from a data source and an output stream is used to write data to a data destination. Just as a stream of water represents a continuous flow of water, a Java stream produces or consumes a continuous flow of data. I/O streams are used to move data from a data source to a Java program, and from a Java program to a data destination.
  1. An input stream enables you to read data from a data source to a Java application.
  2. An output stream enables you to write data from a Java application to a data destination.
Variations of I/O streams
Figure 2-6: Variations of I/O streams: input streams and output streams. An input stream enables a Java program to read data from a data source.
An output stream enables a Java program to write data to a data destination.


The java.util.zip package contains four input stream classes that read data in a compressed format and return it in uncompressed format and four output stream classes that read data in uncompressed format and write in compressed format.
The two main classes are
  1. java.io.InputStream and
  2. java.io.OutputStream

Abstract base Classes

These are abstract base classes for many different subclasses with more-specialized abilities.
Although InputStream and OutputStream are abstract classes, many methods in the class library are only specified to return an InputStream or OutputStream, the not more-specific subclass.
The ByteArrayOutputStream class writes data into the successive components of a byte array using the methods of java.io.OutputStream :
public class ByteArrayOutputStream extends OutputStream

java.io.InputStream

You can read the contents of a web page with this sequence of commands.
String address = "https://www.ooportal.com";
URL u = new URL(address);
URLConnection connection = u.openConnection();
InputStream stream = connection.getInputStream();
Scanner in = new Scanner(stream);

Some of these methods may throw exceptions

Stream Basics Quiz

Click the Quiz link below to take a brief multiple-choice quiz on the basics of streams.
Stream Basics Quiz