在我的程序中,我反复阅读这样的一些文件:
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
发布于 2015-11-17 07:29:27
我通常创建自己的池来缓存文件。只需考虑以下简单的代码:
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删除在某个时间段之后或当堆内存非常低时很少使用的文件。
https://stackoverflow.com/questions/33750987
复制相似问题