Java Streams  «Prev  Next»

Lesson 1

Introduction to Reading Data with Streams

This module introduces developers to how to use streams to read data in Java. In addition, you will learn how to use various methods to make using input streams more efficient.
In this module, you will learn the following:
  1. How to efficiently read data from a stream
  2. How to use the available() method to count available bytes in a stream
  3. How to skip unnecessary data
  4. When to close streams

In this module, all data will be raw bytes. Later modules will show you how to read and write data without explicitly converting it to and from bytes first.

Figure 3.1: A Java application uses FileInputStream and FileOutputStream to read and write byte data from and to files, respectively. It uses FileReader and FileWriter to read and write Unicode text from and to files.
The class is the abstract superclass for all input streams. It declares the three basic methods needed to read bytes of data from a stream. It also has methods for
  1. closing and flushing streams,
  2. checking how many bytes of data are available to be read,
  3. skipping over input,
  4. marking a position in a stream and resetting back to that position, and
  5. determining whether marking and resetting are supported.

public abstract int read() throws IOException
public int read(byte[] data) throws IOException
public int read(byte[] data, int offset, int length) throws IOException
public long skip(long n) throws IOException
public int available() throws IOException
public void close() throws IOException
public synchronized void mark(int readlimit)
public synchronized void reset() throws IOException
public boolean markSupported()

Stream types are uni-directional

This means that if you create an instance of a Java stream, you decide whether you would like to write to it or read from it. You can�t do both at the given time on a single stream.
We can divide the streams into two categories:
  1. Byte streams: Interacts as binary data
  2. Text streams: Interacts as unicode characters

The general interaction is the same for both Java stream types