简体   繁体   English

读取文件一次并多次使用数据

[英]Read the file once and use the data multiple times

I wrote a java class which reads a file and stores each line in an arraylist. 我写了一个Java类,它读取文件并将每一行存储在arraylist中。 I want to access this arraylist large number of times. 我想多次访问此arraylist。 Everytime the class is called to access the arraylist, it reads the file again. 每次调用该类以访问arraylist时,它将再次读取该文件。 I want the file to be read once and then access the arraylist multiple times. 我希望文件被读取一次,然后多次访问arraylist。 How can I do this? 我怎样才能做到这一点?

Store it in a field of the class. 将其存储在类的字段中。 Ie: 即:

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. 例如,将方法synchronized

As Peter noted, if you can read multiple files, then you can use a Map<String, List<String>> 如Peter所述,如果您可以读取多个文件,则可以使用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 sounds like you should be reading the file on construction of the class rather than when accessing it. 听起来您应该在构造类时而不是在访问文件读取文件。 That doesn't necessarily mean in the constructor, mind you - you may well want to have a static factory method that reads the files into an ArrayList , and then passes that list to the real constructor. 请注意,这不一定意味着构造函数中-您可能希望有一个静态工厂方法,该方法将文件读入ArrayList ,然后将该列表传递给实际的构造函数。 This would make the class easier to test (and use in other tests). 这将使该类易于测试(并在其他测试中使用)。

Then you only need to create the class once, and make the rest of your code use the same instance. 然后,您只需要创建一次该类,并使其余代码使用同一实例。 Note that this doesn't require use of the singleton pattern, which would itself make testing harder. 请注意,这并不需要使用Singleton模式,这本身就使测试更难。 It just means propagating the instance to all the code that needs it. 这只是意味着将实例传播到需要它的所有代码。

Maybe you need to make a singleton? 也许您需要单身? Then you will read the file only once - when you create a really new instance of class. 然后,当您创建一个真正新的class实例时,您将只读取一次文件。

如果它是一个Web应用程序,也许您会考虑将其存储在ServletContext或用户HttpSession中,具体取决于文件的更改量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM