Add InputStream to byte[] method to Util.

This commit is contained in:
Oliver Woodman 2015-12-16 20:33:50 +00:00
parent 7f8ddeac39
commit 009b454b69

View File

@ -106,6 +106,24 @@ public final class Util {
return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LEANBACK); return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LEANBACK);
} }
/**
* Converts the entirety of an {@link InputStream} to a byte array.
*
* @param inputStream the {@link InputStream} to be read. The input stream is not closed by this
* method.
* @return a byte array containing all of the inputStream's bytes.
* @throws IOException if an error occurs reading from the stream.
*/
public static byte[] toByteArray(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024 * 4];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
return outputStream.toByteArray();
}
/** /**
* Returns true if the URI is a path to a local file or a reference to a local file. * Returns true if the URI is a path to a local file or a reference to a local file.
* *
@ -699,13 +717,7 @@ public final class Util {
// Read and return the response body. // Read and return the response body.
InputStream inputStream = urlConnection.getInputStream(); InputStream inputStream = urlConnection.getInputStream();
try { try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); return toByteArray(inputStream);
byte scratch[] = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(scratch)) != -1) {
byteArrayOutputStream.write(scratch, 0, bytesRead);
}
return byteArrayOutputStream.toByteArray();
} finally { } finally {
inputStream.close(); inputStream.close();
} }