Video in progress
How do you read a resource file inside a jar, and why doesn't Path work there?
You have to read a classpath file as an InputStream through getClass().getResourceAsStream("/templates/mail.html") or the ClassLoader. A file inside a jar is not a separate file on disk, so Path.of(...) or new File(...) can't find it.
📖 Answer
When you run in the IDE, resources sit in the target/classes directory as ordinary files, and new File("src/main/resources/...") keeps working. When you package a jar and put it on a server: FileNotFoundException.
The right way:
try (InputStream in = MailService.class.getResourceAsStream("/templates/mail.html")) {
if (in == null) throw new IllegalStateException("Shablon topilmadi");
String html = new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
The subtle part is the leading /:
Class.getResourceAsStream("/a.txt"): from the classpath root;Class.getResourceAsStream("a.txt"): relative to the class's package;ClassLoader.getResourceAsStream("a.txt"): always from the root, no/.
Spring has ClassPathResource and @Value("classpath:...") Resource. With those too, take getInputStream(); getFile() doesn't work inside a jar.
Sign up to mark studied questions and save your progress.