英文:
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);
英文:
I have this code:
  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);
    }
  }
Which basically streams from is to the OutputStream provided.
My goal is to cache the is when the flow has completed.
As such I have:
cacheService.cache(key, bytes);
答案1
得分: 1
以下是翻译好的部分:
解决方法是实现一个缓存输出流:
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);
}
英文:
The solution to this is to implement a Caching output stream:
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();
  }
}
And do this:
final CachingOutputStream cachingOutputStream = new CachingOutputStream(outputStream);
flow(inputStream, cachingOutputStream, buff);
cached = cachingOutputStream.getCache();
if(cached != null) {
  cacheService.put(cacheKey, cached);
}
答案2
得分: 0
使用 org.apache.poi.util.IOUtils,
IOUtils.toByteArray(inputStream);
英文:
Using org.apache.poi.util.IOUtils,
IOUtils.toByteArray(inputStream);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论