读取一次文件并多次使用这些数据 [英] Read the file once and use the data multiple times

查看:132
本文介绍了读取一次文件并多次使用这些数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个java类,它读取一个文件,并将每行存储在一个数组列表中。我想大量访问这个数组列表。每次调用该类访问数组列表时,都会再次读取该文件。我希望文件被读取一次,然后多次访问数组列表。我怎么做到这一点?

解决方案

将其存储在类的字段中。即:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆