How to Cache InputStream for Multiple Use

后端 未结 10 1046
庸人自扰
庸人自扰 2020-11-29 05:57

I have an InputStream of a file and i use apache poi components to read from it like this:

POIFSFileSystem fileSystem = new POIFSFileSystem(inputStream);
         


        
10条回答
  •  臣服心动
    2020-11-29 06:34

    This works correctly:

    byte[] bytes = getBytes(inputStream);
    POIFSFileSystem fileSystem = new POIFSFileSystem(new ByteArrayInputStream(bytes));
    

    where getBytes is like this:

    private static byte[] getBytes(InputStream is) throws IOException {
        byte[] buffer = new byte[8192];
    ByteArrayOutputStream baos = new ByteArrayOutputStream(2048);
    int n;
    baos.reset();
    
    while ((n = is.read(buffer, 0, buffer.length)) != -1) {
          baos.write(buffer, 0, n);
        }
    
       return baos.toByteArray();
     }
    

提交回复
热议问题