如何将Java资源作为文件获取? [英] How do I get a Java resource as a File?

查看:70
本文介绍了如何将Java资源作为文件获取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须读取包含字符串列表的文件。我正在尝试按照这篇文章中的建议。两种解决方案都需要使用 FileUtils.readLines ,但使用 String ,而不是文件作为参数。

I have to read a file containing a list of strings. I'm trying to follow the advice in this post. Both solutions require using FileUtils.readLines, but use a String, not a File as the parameter.

Set<String> lines = new HashSet<String>(FileUtils.readLines("foo.txt"));

我需要一个文件

这篇文章 是我的问题,除了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有一个 IOUtils类以及FileUtils,其中包含 readLines 方法类似于FileUtils中的方法。

Apache Commons-IO has an IOUtils class as well as a FileUtils, which includes a readLines method similar to the one in FileUtils.

所以你可以使用 的getResourceAsStream getSystemResourceAsStream 并将结果传递给 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资源作为文件获取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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