code: private static byte[] toByteArray(InputStream input) throws IOException {
      try {
        // safe and fast even if input.available() behaves weird or buggy
        int len = Math.max(256, input.available());
        byte[] buffer = new byte[len];
        byte[] output = new byte[len];
        
        len = 0;
        int n;
        while ((n = input.read(buffer)) >= 0) {
          if (len + n > output.length) { // grow capacity
            byte tmp[] = new byte[Math.max(output.length << 1, len + n)];
            System.arraycopy(output, 0, tmp, 0, len);
            System.arraycopy(buffer, 0, tmp, len, n);
            buffer = output; // use larger buffer for future larger bulk reads
            output = tmp;
          } else {
            System.arraycopy(buffer, 0, output, len, n);
          }
          len += n;
        }
  
        if (len == output.length) return output;
        buffer = null; // help gc
        buffer = new byte[len];
        System.arraycopy(output, 0, buffer, 0, len);
        return buffer;
      } finally {
        input.close();
      }
    }
docs: the following utility methods below are copied from Apache style Nux library - see http://dsd.lbl.gov/nux