0

I am working on a springboot application. I need to load a file that is in resources. The file can be loaded without issues if I run unit tests (maven, just in case)... or even an integration test. But when I run the application say, for real, from the packaged jar, then it can't be found. I have tried with a couple of different ways to reach it but they fail:

java.lang.IllegalArgumentException: resource path-to-file not found.
        at com.google.common.base.Preconditions.checkArgument(Preconditions.java:217) ~[grpc-1.23.jar!/:?]
        at com.google.common.io.Resources.getResource(Resources.java:195) ~[grpc-1.23.jar!/:?]

Another way:

java.io.FileNotFoundException: class path resource [path-to-file] cannot be resolved to absolute file path because it does not exist
        at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:177) ~[spring-core-5.1.7.RELEASE.jar!/:5.1.7.RELEASE]

The file is in WEB-INFO/classes/path-to-file which is coming from src/main/resources/path-to-file in my project.

Thanks for any outside-of-the-box ideas.

Update 1 This made it work from jar, and the code is simple enough:

    ClassPathResource cl = new ClassPathResource(resourcePath);
    URL url = cl.getURL();
    String content;
    try (InputStream in = url.openStream()) {
      content = new String(in.readAllBytes(), StandardCharsets.UTF_8);
    }
    LOG.info("Content from {} is {} bytes long", resourcePath, content.length());
    return content;

The tip came from the answer that is marked as accepted. Thanks!

eftshift0
  • 26,375
  • 3
  • 36
  • 60

1 Answers1

1

May be this would answer your question: Cannot read file within jar file

From my experience, to deal with resource inside jar, i would using InputStream instead

Hưng Chu
  • 1,027
  • 5
  • 11