Read file from resource folder, InputStream is null [duplicate]

拟墨画扇 提交于 2019-12-11 17:51:10

问题


Windows 7, x64, Java 11

How to read a file in resources folder in 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());

I had a similar problem with test/resources.

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());
}

But what worked for test/resources does not work for java/resources.

What happened in Java-11 or in my code?


I tried this

URL url = ClassLoaderUtil.getResource("test.csv", YourCallingClass.class);
Path path = Paths.get(url.toURI());
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);

And this

// 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
}

Other examples

And this does not help

 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());
}

回答1:


I solved it!!!!

maven

I build my project with maven. After I added a file to resources, it did not go to target directory.

Rebuild the project.

mvn clean install


来源:https://stackoverflow.com/questions/55409522/read-file-from-resource-folder-inputstream-is-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!