Fireburn
Fireburn

Reputation: 1021

InputStream to byte array

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

Upvotes: 1

Views: 604

Answers (2)

RoshanS
RoshanS

Reputation: 129

Using org.apache.poi.util.IOUtils,

IOUtils.toByteArray(inputStream);

Upvotes: 0

quarks
quarks

Reputation: 35282

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

Upvotes: 1

Related Questions