How do I load a file from resource folder? How do I load a file from resource folder? java java

How do I load a file from resource folder?


Try the next:

ClassLoader classloader = Thread.currentThread().getContextClassLoader();InputStream is = classloader.getResourceAsStream("test.csv");

If the above doesn't work, various projects have been added the following class: ClassLoaderUtil1 (code here).2

Here are some examples of how that class is used:

src\main\java\com\company\test\YourCallingClass.javasrc\main\java\com\opensymphony\xwork2\util\ClassLoaderUtil.javasrc\main\resources\test.csv
// java.net.URLURL url = ClassLoaderUtil.getResource("test.csv", YourCallingClass.class);Path path = Paths.get(url.toURI());List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
// java.io.InputStreamInputStream inputStream = ClassLoaderUtil.getResourceAsStream("test.csv", YourCallingClass.class);InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);BufferedReader reader = new BufferedReader(streamReader);for (String line; (line = reader.readLine()) != null;) {    // Process line}

Notes

  1. See it in The Wayback Machine.
  2. Also in GitHub.


Try:

InputStream is = MyTest.class.getResourceAsStream("/test.csv");

IIRC getResourceAsStream() by default is relative to the class's package.

As @Terran noted, don't forget to add the / at the starting of the filename


Here is one quick solution with the use of Guava:

import com.google.common.base.Charsets;import com.google.common.io.Resources;public String readResource(final String fileName, Charset charset) throws IOException {        return Resources.toString(Resources.getResource(fileName), charset);}

Usage:

String fixture = this.readResource("filename.txt", Charsets.UTF_8)