Windows 7 ,x64, Java 11
如何读取main中资源文件夹中的文件。
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
// Input stream is null.
InputStream is = App.class.getResourceAsStream(filename);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
return br.lines().collect(Collectors.toList());
我在测试/资源中遇到了类似的问题。
private static List<String> readLines(final String filename) {
try (final InputStreamReader isr = new FileReader(getFileFromResource(filename));
final BufferedReader br = new BufferedReader(isr)) {
return br.lines().collect(Collectors.toList());
} catch (IOException e) {
throw new RuntimeException(String.format("Failed to read file: %s", filename), e);
}
}
private static File getFileFromResource(final String filename) {
///////// App.class.getResource is NULL
final URL url = App.class.getClassLoader().getResource(filename);
if (url == null) {
throw new RuntimeException(String.format("Failed to read resource %s from resources folder.", filename));
}
return new File(url.getFile());
}
但是对于测试/资源有效的方法不适用于 java / resources 。
在Java-11或我的代码中发生了什么?
我尝试了this
URL url = ClassLoaderUtil.getResource("test.csv", YourCallingClass.class);
Path path = Paths.get(url.toURI());
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
还有这个
// java.io.InputStream
InputStream 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
}
this并没有帮助
private List<String> readLines(String filename) {
// InputStream is null
InputStream is = getClass().getClassLoader()
.getResourceAsStream(filename);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
return br.lines().collect(Collectors.toList());
}