Java: InputStream转化为byte数组
在commons-io包中org.apache.commons.io.IOUtils类的toByteArray(InputStream input)已经有实现了,我们可以参考下思路,完成我们的方法,我们可以用类似下面的代码实现inputStream转化为byte[]数组
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(); }
可利用此Api 读取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; }