Skip to content

Instantly share code, notes, and snippets.

@li2
Last active March 20, 2018 07:05
Show Gist options
  • Save li2/69420671e7f029ee7d1bad7205aba10b to your computer and use it in GitHub Desktop.
Save li2/69420671e7f029ee7d1bad7205aba10b to your computer and use it in GitHub Desktop.
read bytes stream from IO #tags: java
class IOHelper {
public byte[] readBytes(InputStream inputStream) throws IOException {
// this dynamically extends to take the bytes you read
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
// this is storage overwritten on each iteration with bytes
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// we need to know how may bytes were read to write them to the byteBuffer
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
byteBuffer.close();
// and then we can return your byte array.
return byteBuffer.toByteArray();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment