Reading Bytes From Any InputStream

Reading Bytes From Any InputStream

Most of the time, we do get available bytes in one stroke by calling read() API in InputStream.

long length = is.available();
byte[] bytes = new byte[(int) length];
is.read(bytes);
System.out.println(new String(bytes));

The above given code may not work for InputStream which reads data from socket. Means, this will not read full data from the stream, reason could be
  • network delay in transmitting content
  • mounted filesystem unlinked
  • message size is exceeds TCP window size
  • etc.,
.

Hence, the following code will make sure and helps us to check whether all the bytes are received or not.


public static byte[] getBytesFromInputStream(InputStream is)
throws IOException {

// Get the size of the file
long length = is.available();

if (length > Integer.MAX_VALUE) {
// File is too large
}

// Create the byte array to hold the data
byte[] bytes = new byte[(int) length];

// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}

// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file ");
}

// Close the input stream and return bytes
is.close();
return bytes;
}

Read more : Reverse Reading

Unix Commands