首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >缓存FileInputStream

缓存FileInputStream
EN

Stack Overflow用户
提问于 2015-11-17 07:02:56
回答 1查看 863关注 0票数 1

在我的程序中,我反复阅读这样的一些文件:

代码语言:javascript
复制
String myLetter = "CoverSheet.rtf"; // actually has a full path
FileInputStream in = new FileInputStream(myLetter);
letterSection.importRtfDocument(in);
in.close();

因为有许多小文件是要用importRtfDocument添加到文档中的组件,而且在运行过程中要生成数千个字母,所以处理非常慢。

importRtfDocument方法来自我正在使用的一个库,需要给它一个FileInputStream。这就是我困惑的地方。我尝试了一些方法,比如为类中的每个文件声明一个FileInputStream并保持其打开--但是不支持reset()

我看过其他类似的问题,如:

How to Cache InputStream for Multiple Use

然而,似乎没有人能解决我的问题,也就是说,我如何缓存FileInputStream

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-17 07:29:27

我通常创建自己的池来缓存文件。只需考虑以下简单的代码:

代码语言:javascript
复制
class CachedPool {
    private Map<URI, CachedFile> pool = new HashMap<>();

    public CachedPool(){
    }

    public <T> T getResource(URI uri) {
        CachedFile file;
        if(pool.containsKey(uri)){
            file = pool.get(uri);
        } else {
            file = new CachedFile(uri);   // Injecting point to add resources
            pool.put(uri, file);
        }
        return file.getContent();
    }
}

class CachedFile {
    private URI uri;
    private int counter;
    private Date cachedTime;
    private Object content;

    public CachedFile(URL uri){
        this.url = uri;
        this.content = uri.toURL().getContent();
        this.cachedTime = new Date();
        this.counter = 0;
    }

    public <T> T getContent(){
        counter++;
        return (T) content;
    }

    /** Override equals() and hashCode() **/
    /** Write getters for all instance variables **/
}

您可以使用counter of CachedFile删除在某个时间段之后或当堆内存非常低时很少使用的文件。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33750987

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档