InputStream 到字节数组

InputStream to byte array

我有这个代码:

  private static void flow(InputStream is, OutputStream os, byte[] buf)
      throws IOException {
    int numRead;
    while ((numRead = is.read(buf)) >= 0) {
      os.write(buf, 0, 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);
}

使用org.apache.poi.util.IOUtils,

IOUtils.toByteArray(inputStream);