如何缓存InputStream以便多次使用
我有一个文件的InputStream,我使用apache poi组件像这样从中读取:
POIFSFileSystem fileSystem = new POIFSFileSystem(inputStream);问题是我需要多次使用同一流,并且POIFSFileSystem在使用后会关闭流。
缓存来自输入流的数据,然后将更多输入流提供给不同的POIFSFileSystem的最佳方法是什么?
编辑1:
高速缓存是指存储供以后使用,而不是用来加速应用程序。将输入流读入数组或字符串,然后为每次使用创建输入流是否更好?
编辑2:
抱歉,我再次提出问题,但是在桌面和Web应用程序中工作时,条件有些不同。首先,我从tomcat
Web应用程序中的org.apache.commons.fileupload.FileItem获得的InputStream不支持标记,因此无法重置。
其次,我希望能够将文件保留在内存中,以便在处理文件时更快地访问文件并减少io问题。
回答:
您可以使用以下版本来 修饰 传递给 POIFSFileSystem的 InputStream
,该版本在调用close()时会使用reset()进行响应:
class ResetOnCloseInputStream extends InputStream {    private final InputStream decorated;
    public ResetOnCloseInputStream(InputStream anInputStream) {
        if (!anInputStream.markSupported()) {
            throw new IllegalArgumentException("marking not supported");
        }
        anInputStream.mark( 1 << 24); // magic constant: BEWARE
        decorated = anInputStream;
    }
    @Override
    public void close() throws IOException {
        decorated.reset();
    }
    @Override
    public int read() throws IOException {
        return decorated.read();
    }
}
回答:
static void closeAfterInputStreamIsConsumed(InputStream is)        throws IOException {
    int r;
    while ((r = is.read()) != -1) {
        System.out.println(r);
    }
    is.close();
    System.out.println("=========");
}
public static void main(String[] args) throws IOException {
    InputStream is = new ByteArrayInputStream("sample".getBytes());
    ResetOnCloseInputStream decoratedIs = new ResetOnCloseInputStream(is);
    closeAfterInputStreamIsConsumed(decoratedIs);
    closeAfterInputStreamIsConsumed(decoratedIs);
    closeAfterInputStreamIsConsumed(is);
}
回答:
您可以读取整个文件并以byte [](读取模式)将其传递给ByteArrayInputStream
以上是 如何缓存InputStream以便多次使用 的全部内容, 来源链接: utcz.com/qa/427090.html








