问题描述
我必须读取包含字符串列表的文件。我正在尝试按照 会是我的问题,除了OP完全被劝阻使用文件。如果我想使用Apache方法,我需要一个文件,这是我最初解决问题的首选方法。
This post would be my question, except the OP was dissuaded from using files entirely. I need a file if I want to use the Apache method, which is the my preferred solution to my initial problem.
我的文件很小(一百行左右)每个程序实例都有一个单例,所以我不必担心在内存中有另一个文件副本。因此我可以使用更基本的方法来读取文件,但到目前为止看起来像 FileUtils.readLines
可能更清晰。我如何从资源到文件。
My file is small (a hundred lines or so) and a singleton per program instance, so I do not need to worry about having another copy of the file in memory. Therefore I could use more basic methods to read the file, but so far it looks like FileUtils.readLines
could be much cleaner. How do I go from resource to file.
推荐答案
Apache Commons-IO有一个以及FileUtils,其中包含类似于FileUtils中的方法。
Apache Commons-IO has an IOUtils class as well as a FileUtils, which includes a readLines
method similar to the one in FileUtils.
所以你可以使用或并将结果传递给 IOUtils.readLines
以获取列表< String>
您文件的内容:
So you can use getResourceAsStream
or getSystemResourceAsStream
and pass the result of that to IOUtils.readLines
to get a List<String>
of the contents of your file:
List<String> myLines = IOUtils.readLines(ClassLoader.getSystemResourceAsStream("my_data_file.txt"));
这篇关于如何将Java资源作为文件获取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!