Skip to content

Instantly share code, notes, and snippets.

@kelvinewilliams
Last active December 23, 2015 02:29
Show Gist options
  • Save kelvinewilliams/6567437 to your computer and use it in GitHub Desktop.
Save kelvinewilliams/6567437 to your computer and use it in GitHub Desktop.
Java: Reading InputStreams
/* One way to read an InputStream... NOT Recommended when dealing with some InputStreams, especially if that is from a network connection. */
try {
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
// do something with the bytes read from the InputStream
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
/* Better way to read an InputStream. */
try {
byte[] bytes = new byte[1024];
int r = 0;
while ((r = inputStream.read(bytes)) >= 0) {
// do something with the bytes read from the InputStream
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment