How to get Java resource as a file?

I need to read a file containing a list of lines. I try to follow the advice in this post . Both solutions require the use of FileUtils.readLines , but use String rather than File as the parameter.

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

I need a File .

This post would be my question, except that the OP was discouraged from using the entire file. I need a file if I want to use the Apache method, which is my preferred solution for my original problem.

My file is small (hundreds of lines or so) and a single-screen copy of the program, so I do not need to worry about another copy of the file in memory. So I could use simpler methods to read the file, but it still looks like FileUtils.readLines can be much cleaner. How to go from resource to file.

+6
source share
3 answers

Apache Commons-IO has an IOUtils class , as well as a FileUtils class that includes a readLines method similar to a FileUtils file.

So you can use getResourceAsStream or getSystemResourceAsStream and pass the result of this IOUtils.readLines to get a List<String> contents of your file:

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

I assume that the file you want to read is a true resource in your class path, and not just any arbitrary file that you can simply access through new File("path_to_file"); .

Try using ClassLoader , where resource is a String representation of the path to your resource file in your class path.

Valid String values ​​for resource may include:

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

and the path is not limited to com.company

Relevant code to get File not in 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 

Alternatively, if your resource is in a JAR, you will need to use Class.getResourceAsStream(resource); and scroll through the file using BufferedReader to simulate a call to readLines() .

+2
source

using a resource to read a file into a string:

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

using input stream:

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

Source: https://habr.com/ru/post/952687/


All Articles