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);
}