From 009b454b6997ebd774fc7df8750f1d88e2c1939f Mon Sep 17 00:00:00 2001 From: Oliver Woodman Date: Wed, 16 Dec 2015 20:33:50 +0000 Subject: [PATCH] Add InputStream to byte[] method to Util. --- .../google/android/exoplayer/util/Util.java | 26 ++++++++++++++----- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/library/src/main/java/com/google/android/exoplayer/util/Util.java b/library/src/main/java/com/google/android/exoplayer/util/Util.java index ae9db72916..5576ec6165 100644 --- a/library/src/main/java/com/google/android/exoplayer/util/Util.java +++ b/library/src/main/java/com/google/android/exoplayer/util/Util.java @@ -106,6 +106,24 @@ public final class Util { 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. * @@ -699,13 +717,7 @@ public final class Util { // Read and return the response body. InputStream inputStream = urlConnection.getInputStream(); try { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - byte scratch[] = new byte[1024]; - int bytesRead; - while ((bytesRead = inputStream.read(scratch)) != -1) { - byteArrayOutputStream.write(scratch, 0, bytesRead); - } - return byteArrayOutputStream.toByteArray(); + return toByteArray(inputStream); } finally { inputStream.close(); }