如何解决InputStream到字节数组
我有此代码:
private static void flow(InputStream is,OutputStream os,byte[] buf)
throws IOException {
int numRead;
while ((numRead = is.read(buf)) >= 0) {
os.write(buf,numRead);
}
}
基本上从is
流到提供的OutputStream
。
我的目标是在流程完成后缓存is
。
我这样:
cacheService.cache(key,bytes);
解决方法
解决方案是实现缓存输出流:
public class CachingOutputStream extends OutputStream {
private final OutputStream os;
private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
public CachingOutputStream(OutputStream os) {
this.os = os;
}
public void write(int b) throws IOException {
try {
os.write(b);
baos.write(b);
} catch (Exception e) {
if(e instanceof IOException) {
throw e;
} else {
e.printStackTrace();
}
}
}
public byte[] getCache() {
return baos.toByteArray();
}
public void close() throws IOException {
os.close();
}
public void flush() throws IOException {
os.flush();
}
}
然后执行以下操作:
final CachingOutputStream cachingOutputStream = new CachingOutputStream(outputStream);
flow(inputStream,cachingOutputStream,buff);
cached = cachingOutputStream.getCache();
if(cached != null) {
cacheService.put(cacheKey,cached);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。