I have a jar with the following structure on my jar:
I am trying to read the file under custom/file.txt
but it’s throwing me an error:
java.io.FileNotFoundException: URL cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/Users/josh/github/gov-aus-api/app/target/gov-aus-api-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/custom/file.txt
My code is very simple:
@Component("LoaderImpl")
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
public class LoaderImpl {
@PostConstruct
public void init() {
FileReader in = null;
try {
URL url = getClass().getResource("/custom/file.txt");
File file = ResourceUtils.getFile(url);
// File file = ResourceUtils.getFile("classpath:custom/file.txt");
// Resource resource = new ClassPathResource("custom/file.txt");
// File file = resource.getFile();
in = new FileReader(file);
} catch (Exception e) {
throw new RuntimeException("Cant load file");
}
}
}
Same code working running on IntelliJ but what’s not working when try to run .jar file? How can I read it from .jar and inside my Intellij?
Usinig Java 17 and Spring 2.7.x
16
Method getFile(String) searches the file system. However, you say that the file – file.txt – is in the JAR file. Hence method getFile(String)
is not appropriate.
You can use method getResource as in…
java.net.URL url = getClass().getResource("/custom/file.txt"); // Note leading slash
ResourceUtils.getFile(url.toURI());
You wrote (in your question):
Same code working running on IntelliJ but what’s not working when try to run .jar file
That’s because when you run it from IntelliJ, it is using the file system (and not the JAR).
3