獲取到一個inputstream后,可能要多次利用它進行read的操作。由於流讀過一次就不能再讀了,而InputStream對象本身不能復制,而且它也沒有實現Cloneable接口。
實現思路:
1、先把InputStream轉化成ByteArrayOutputStream
2、后面要使用InputStream對象時,再從ByteArrayOutputStream轉化回來
代碼實現如下:
private static ByteArrayOutputStream cloneInputStream(InputStream input) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = input.read(buffer)) > -1) {
baos.write(buffer, 0, len);
}
baos.flush();
return baos;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
適用於文件不是很大的流,因為是直接放緩存的。
關於
參考: