public static final int READ_BUFFER_SIZE = 1024; /** * 讀取流中的字符到數組 * @param in 該方法執行完成不會關閉流 * @param limit 讀取大小限制 * @return * @throws IOException */ public static byte[] readStreamAsByteArray(InputStream in, int limit) throws IOException { if (in == null) { return new byte[0]; } ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[READ_BUFFER_SIZE]; int len = -1; int temp = limit - READ_BUFFER_SIZE; while ((len = in.read(buffer)) != -1) { output.write(buffer, 0, len); if(output.size() > temp) { if(output.size() == limit) { break; } byte[] buffer2 = new byte[limit - output.size()]; while ((len = in.read(buffer2)) != -1) { output.write(buffer2, 0, len); if(output.size() == limit) { break; } buffer2 = new byte[limit - output.size()]; } break; } } return output.toByteArray(); }
上面代碼用於從InputStream中讀取特定長度的數據,把文件分斷處理時用到