Issue Description
String resource = ZipFileOutDemo.class.getClassLoader().getResource("1.txt").getPath();
1.txt is put under folder “resources”.
This code could be able to run within IDE (Intellij), but not able to run after packaged to a jar. Got below error:
java.io.FileNotFoundException: file:/path/to/project/target/javabasics-1.0-SNAPSHOT-jar-with-dependencies.jar!/1.txt (No such file or directory)
Root Cause
A Resource in Java is not a File. If the Resource is inside a JAR, for example, you can’t access it like a File. You have to explode the JAR first
Solution
Replace getResource()
with getResourceAsStream()
.
Sample code:
https://github.com/danielsunzhongyuan/puruan-training/blob/main/javabasics/src/main/java/org/github/zsun/java/puruantraining/javabasics/chapter4/ZipFileOutDemo.java
Reference
- https://stackoverflow.com/questions/22682384/filenotfoundexception-with-getresources
- https://blog.csdn.net/haoxiaoyong1014/article/details/107452595