Read file from resource folder, InputStream is nul

2019-08-29 03:47发布

问题:

This question already has an answer here:

  • How do I load a file from resource folder? 14 answers

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


标签: java java-11