Tuesday, March 31, 2009

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];
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
return bytes;

Read more : Reverse Reading

Recent Posts

Unix Commands | List all My Posts


This blog intended to share the knowledge and contribute to JAVA Community such a way that by providing samples and pointing right documents/webpages. We try to give our knowledege level best and no guarantee can be claimed on truth. Copyright and Terms of Policy refer blogspot.com