Java IO: InputStream

Connect with me:  
  Jenkov.com - News

The InputStream class is the base class (superclass) of all input streams in the Java IO API. Subclasses include the FileInputStream, BufferedInputStream and the PushbackInputStream among others. To see a full list of streams, go to the bottom table of the Java IO Overview page.

Table of contents:

Java InputStream Example

Java InputStream's are used for reading byte based data, one byte at a time. Here is a Java InputStream example:

InputStream inputstream = new FileInputStream("c:\\data\\input-text.txt");

int data = inputstream.read();
while(data != -1) {
  //do something with data...
  doSomethingWithData(data);

  data = inputstream.read();
}
inputstream.close();

Note: The proper exception handling has been skipped here for the sake of clarity. To learn more about correct exception handling, go to Java IO Exception Handling.

read()

The read() method of an InputStream returns an int which contains the byte value of the byte read. Here is an InputStream read() example:

int data = inputstream.read();

You can case the returned int to a char like this:

char aChar = (char) data;

Subclasses of InputStream may have alternative read() methods. For instance, the DataInputStream allows you to read Java primitives like int, long, float, double, boolean etc. with its corresponding methods readBoolean(), readDouble() etc.

End of Stream

If the read() method returns -1, the end of stream has been reached, meaning there is no more data to read in the InputStream. That is, -1 as int value, not -1 as byte or short value. There is a difference here!

When the end of stream has been reached, you can close the InputStream.

InputStreams and Sources

An InputStream is typically always connected to some data source, like a file, network connection, pipe etc. This is also explained in more detail in the Java IO Overview text.

Connect with me:
     
Newsletter - Get all my free tips!