如何将 Java 资源作为文件获取?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18497534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 08:36:07  来源:igfitidea点击:

How do I get a Java resource as a File?

javafilejarresources

提问by djechlin

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 Fileas the parameter.

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

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

I need a File.

我需要一个File.

This postwouldbe 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.

这篇文章是我的问题,除了 OP 被劝阻不要完全使用文件。如果我想使用 Apache 方法,我需要一个文件,这是我最初问题的首选解决方案。

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.readLinescould be much cleaner. How do I go from resource to file.

我的文件很小(一百行左右),每个程序实例一个单例,所以我不需要担心内存中还有另一个文件副本。因此,我可以使用更基本的方法来读取文件,但到目前为止,它看起来FileUtils.readLines可能要干净得多。我如何从资源转到文件。

采纳答案by matt

Apache Commons-IO has an IOUtils classas well as a FileUtils, which includes a readLinesmethodsimilar to the one in FileUtils.

Apache Commons-IO 有一个IOUtils 类和一个FileUtils,其中包含一个类似于FileUtils 中readLines方法

So you can use getResourceAsStreamor getSystemResourceAsStreamand pass the result of that to IOUtils.readLinesto get a List<String>of the contents of your file:

所以,你可以使用getResourceAsStreamgetSystemResourceAsStream与合格的结果IOUtils.readLines获得List<String>的文件的内容:

List<String> myLines = IOUtils.readLines(ClassLoader.getSystemResourceAsStream("my_data_file.txt"));

回答by JoshDM

I am assuming the file you want to read is a true resource on your classpath, and not simply some arbitrary file you could just access via new File("path_to_file");.

我假设您要读取的文件是您的类路径上的真正资源,而不仅仅是您可以通过new File("path_to_file");.

Try the following using ClassLoader, where resourceis a Stringrepresentation of the path to your resource file in your class path.

尝试使用以下方法ClassLoader,其中resourceString类路径中资源文件路径的表示形式。

Valid Stringvalues for resourcecan include:

有效String的值resource可以包括:

  • "foo.txt"
  • "com/company/bar.txt"
  • "com\\company\\bar.txt"
  • "\\com\\company\\bar.txt"
  • "foo.txt"
  • "com/company/bar.txt"
  • "com\\company\\bar.txt"
  • "\\com\\company\\bar.txt"

and path is not limited to com.company

并且路径不限于 com.company

Relevant code to get a Filenot in a JAR:

File在 JAR 中获取not 的相关代码:

File file = null;

try {

    URL url = null;
    ClassLoader classLoader = {YourClass}.class.getClassLoader(); 

    if (classLoader != null) {

        url = classLoader.getResource(resource);
    }

    if (url == null) {

        url = ClassLoader.getSystemResource(resource);
    }

    if (url != null) {

        try {

            file = new File(url.toURI());

        } catch (URISyntaxException e) {

            file = new File(url.getPath());
        }
    }

} catch (Exception ex) { /* handle it */ }

// file may be null

Alternately, if your resource is in a JAR, you will have to use Class.getResourceAsStream(resource);and cycle through the file using a BufferedReaderto simulate the call to readLines().

或者,如果您的资源在 JAR 中,您将必须使用Class.getResourceAsStream(resource);并循环使用 文件BufferedReader来模拟对readLines().

回答by Barry Knapp

using a resource to read the file to a string:

使用资源将文件读取为字符串:

String contents = 
 FileUtils.readFileToString(
  new File(this.getClass().getResource("/myfile.log").toURI()));

using inputstream:

使用输入流:

List<String> listContents = 
 IOUtils.readLines(
  this.getClass().getResourceAsStream("/myfile.log"));