读取一次文件并多次使用这些数据 [英] Read the file once and use the data multiple times
问题描述
将其存储在类的字段中。即:
public class Foo {
private List< String>列表;
公开列表< String> readData(){
if(list!= null){
return list;
}
//读取数据。
请注意,如果在多线程环境中使用它必须采取额外的措施。例如,在方法中放置 synchronized
。
正如Peter指出的,如果你可以读取多个文件,那么你可以使用 Map< String,List< String>>
另外需要注意的是,这个班如果您创建了多个实例,则不会达到所需的效果。
I wrote a java class which reads a file and stores each line in an arraylist. I want to access this arraylist large number of times. Everytime the class is called to access the arraylist, it reads the file again. I want the file to be read once and then access the arraylist multiple times. How can I do this?
解决方案 Store it in a field of the class. I.e.:
public class Foo {
private List<String> list;
public List<String> readData() {
if (list != null) {
return list;
}
// do the reading.
}
}
Note that if this is used in a multithreaded environment you'd have to take extra measures. For example put synchronized
on the method.
As Peter noted, if you can read multiple files, then you can use a Map<String, List<String>>
Another note is that you should use only one instance of this class. If you create multiple instances you won't have the desired effect.
这篇关于读取一次文件并多次使用这些数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!