java中InputStream轉化為byte[]陣列[轉載]
阿新 • • 發佈:2019-02-02
在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(); }
下面是IOUtils中摘錄出與toByteArray相關的方法
org.apache.commons.io.IOUtils.toByteArray 方法如下: public static byte[] toByteArray(InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); copy(input, output); return output.toByteArray(); } public static int copy(InputStream input, OutputStream output) throws IOException { long count = copyLarge(input, output); if (count > 2147483647L) { return -1; } return (int)count; } public static long copyLarge(InputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[4096]; long count = 0L; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; }