Java 缓存FileInputStream
在我的程序中,我反复阅读大量类似以下内容的文件:Java 缓存FileInputStream,java,caching,fileinputstream,Java,Caching,Fileinputstream,在我的程序中,我反复阅读大量类似以下内容的文件: String myLetter = "CoverSheet.rtf"; // actually has a full path FileInputStream in = new FileInputStream(myLetter); letterSection.importRtfDocument(in); in.close(); 由于有许多小文件是要添加到带有importRtfDocument的文档中的组件,并且一次运行要生成数千封信,因此处理速
String myLetter = "CoverSheet.rtf"; // actually has a full path
FileInputStream in = new FileInputStream(myLetter);
letterSection.importRtfDocument(in);
in.close();
由于有许多小文件是要添加到带有importRtfDocument
的文档中的组件,并且一次运行要生成数千封信,因此处理速度相当慢
importRtfDocument
方法来自我正在使用的库,需要提供一个FileInputStream
。这就是我被难倒的地方。我尝试了一些方法,比如为类中的每个文件声明一个FileInputStream
,并使它们保持打开状态,但是reset()
不受支持
我看过其他类似的问题,比如:
然而,似乎没有人能解决我的问题,也就是说,我如何缓存
文件输入流?我通常创建自己的池来缓存文件。只需考虑以下简单代码:
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 **/
}
类CachedPool{
私有映射池=新的HashMap();
公共CachedPool(){
}
公共获取资源(URI){
缓存文件;
if(pool.containsKey(uri)){
file=pool.get(uri);
}否则{
file=newcachedFile(uri);//注入点以添加资源
put(uri,文件);
}
返回文件.getContent();
}
}
类缓存文件{
私有URI;
专用int计数器;
私有日期缓存时间;
私有对象内容;
公共缓存文件(URL uri){
this.url=uri;
this.content=uri.toURL().getContent();
this.cachedTime=新日期();
这个计数器=0;
}
公共T getContent(){
计数器++;
返回(T)内容;
}
/**重写equals()和hashCode()**/
/**为所有实例变量编写getter**/
}
您可以使用CachedFile
的counter
删除在特定时间段后或堆内存非常低时很少使用的文件。您的答案很有希望。最重要的是,Turophile需要创建FileInputStream的子类,以便从缓存中为他正在使用的库提供数据,对吗?