Java: InputStream into a byte array

In commons-io package toByteArray org.apache.commons.io.IOUtils class (InputStream input) has been achieved, we can refer to the idea, in our approach, we can use the following code to achieve a similar conversion of byte inputStream [] array

public static byte[] toByteArray(InputStream input) throws IOException {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    byte[] buffer = new byte[4096];
    int n = 0;
    while (-1 != (n = input.read(buffer))) {
        output.write(buffer, 0, n);
    }
    return output.toByteArray();
}

Can use this Api read the contents of binary files stored on android sdcard:

  public static byte[] readBinaryFileContent(Context context, Uri uri) {
        if (context == null || uri == null) return null;
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            if (inputStream == null) return null;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte buff[] = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buff)) != -1) {
                baos.write(buff, 0, len);
            }
            baos.flush();
            return baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace ();
        }
        return null;
    }

 

Guess you like

Origin www.cnblogs.com/yongdaimi/p/12367746.html