Last active
December 23, 2015 02:29
-
-
Save kelvinewilliams/6567437 to your computer and use it in GitHub Desktop.
Java: Reading InputStreams
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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