Reading several bytes at once

The basic read() method reads a byte at a time. This is less than perfectly efficient. The following two overloaded variants read multiple bytes into an array of bytes.

 public int read(byte[] data) throws IOException
 public int read(byte[] data, int offset, int length) throws IOException

The first method tries to read enough bytes to fill the array b. The second method reads length bytes from the input stream and stores them into the array b starting at position offset.

These methods block until there is some data available. Then they read as many bytes as they can into b, or until they've read length bytes.

These methods then return the number of bytes actually read. You should not assume that the array will be filled or that length bytes will actually have been read. If the end of stream is encountered, -1 is returned.

Previous | Next | Top | Cafe con Leche

Copyright 2000 Elliotte Rusty Harold
Last Modified January 22, 2000