I have this very specific need wherein a file is loaded from classpath and the same is used in another module which needs it's absolute path. What are the possible ways an absolute path of a file loaded via classpath can be deduced ?
Asked
Active
Viewed 5.6k times
2 Answers
35
Use ClassLoader.getResource() instead of ClassLoader.getResourceAsStream() to get a URL. It will be, by definition, always absolute.
You can then use openConnection() on the URL to load the content. I'm often using this code:
public ... loadResource(String resource) {
URL url = getClass().getClassLoader().getResource(resource);
if (url == null) {
throw new IllegalArgumentException("Unable to find " + resource + " on classpath);
}
log.debug("Loading {}", url); // Will print a file: or jar:file: URL with absolute path
try(InputStream in = resource.openConnection()) {
...
}
}
Aaron Digulla
- 310,263
- 103
- 579
- 794
-
3Even though for most of java developers this answer is obvious for some it's not that obvious which class the method ```getResource()``` is, should consider adding it or pointing to the javadoc, and as it's stated in this comment if you use getResource() from class or classloader it may behave differently: http://stackoverflow.com/questions/2593154/get-a-resource-using-getresource#comment2601113_2593175 – Panthro May 20 '15 at 13:24
-
needs a better example – bharal Oct 20 '20 at 16:21
33
jmj
- 232,312
- 42
- 391
- 431
-
Can you explain more instead of giving a link because its not working 'classLoader.getResource("/path/in/classpath").getFile();' – user55924 May 09 '17 at 17:02
-
1link is still valid and alive. however I updated to latest stable version https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getResource(java.lang.String) – jmj May 09 '17 at 17:33
-
3You need: `SomeClassOfYours.getClass().getClassLoader().getResource` – Stijn de Witt Oct 02 '17 at 18:02