简体   繁体   English

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

[英]How do I get a Java resource as a File?

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. 两种解决方案都需要使用FileUtils.readLines ,但使用String而不是File作为参数。

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

I need a File . 我需要一个File

This post would be my question, except the OP was dissuaded from using files entirely. 这篇文章 是我的问题,除了OP被完全禁止使用文件。 I need a file if I want to use the Apache method, which is the my preferred solution to my initial problem. 如果我想使用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.readLines could be much cleaner. 因此,我可以使用更基本的方法来读取文件,但到目前为止看起来像FileUtils.readLines可能更清洁。 How do I go from resource to file. 我如何从资源到文件。

Apache Commons-IO has an IOUtils class as well as a FileUtils, which includes a readLines method similar to the one in FileUtils. Apache Commons-IO有一个IOUtils类和一个FileUtils ,它包含一个类似于FileUtils中readLines方法

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: 因此,您可以使用getResourceAsStreamgetSystemResourceAsStream并将结果传递给IOUtils.readLines以获取文件内容的List<String>

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

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");访问的任意文件new File("path_to_file"); .

Try the following using ClassLoader , where resource is a String representation of the path to your resource file in your class path. 使用ClassLoader尝试以下操作,其中resource是类路径中资源文件路径的String表示形式。

Valid String values for resource can include: resource有效String值可以包括:

  • "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 File not in a JAR: 获取File不在JAR中的相关代码:

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); 或者,如果您的资源位于JAR中,则必须使用Class.getResourceAsStream(resource); and cycle through the file using a BufferedReader to simulate the call to readLines() . 并使用BufferedReader遍历文件以模拟对readLines()的调用。

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"));

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

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