0

I have the following prefix:

String prefix = TemplatesReader.class.getClassLoader().getResource("templates/").getPath();

and have method

public byte[] read(String pathToTemplate) {
   return Files.readAllBytes(Paths.get(prefix + pathToTemplate));
}

in intellij idea works correctly, but when starting jar an error occurs:

java.nio.file.NoSuchFileException: file:/app.jar!/BOOT-INF/classes!/templates/request-orders/unmarked/RequestOrderUnmarked.pdf

  • Does this answer your question? [this.getClass().getClassLoader().getResource("...") and NullPointerException](https://stackoverflow.com/questions/3803326/this-getclass-getclassloader-getresource-and-nullpointerexception) – alain.janinm Dec 09 '21 at 13:53
  • @alain.janinm this is not helped – Maria Malova Dec 09 '21 at 14:00
  • Are you using any plugin or script for packaging. In this case you should share more info for helping you. – sigur Dec 09 '21 at 14:01
  • org.apache.maven.plugins maven-compiler-plugin 11 11 – Maria Malova Dec 09 '21 at 14:11
  • 2
    Your mistake was calling `getPath()`. That *does not* return a valid file name, it merely returns the path portion of a URL. A resource inside a .jar is just part of a .jar file, not a separate file. You cannot use Path and Files to read it. You can, however, use `getResourceAsStream` to read it. – VGR Dec 09 '21 at 14:18
  • Could you decompress the jar and verify if your template exist? – JRichardsz Dec 09 '21 at 21:30

1 Answers1

1

You must not assume that a resource is a file. When the resource is inside a .jar file, it is a part of that .jar file; it is no longer a separate file at all.

You cannot use Files or Paths to read the resource.

You cannot use the getPath() method of URL. It does not return a file name. It only returns the path portion of the URL (that is, everything between the URL’s scheme/authority and its query portion), which is not a file path at all.

Instead, read the resource using getResourceAsStream:

private static final String RESOURCE_PREFIX = "/templates/";

public byte[] read(String pathToTemplate)
throws IOException {
    try (InputStream stream = TemplatesReader.class.getResource(
        RESOURCE_PREFIX + pathToTemplate)) {

        return stream.readAllBytes();
    }
}
VGR
  • 40,506
  • 4
  • 48
  • 63