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: ClassLoaderUtil
1 (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
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)