I have a file under resources directory as: resources/MOResponse/UploadResponse.json
Now when I use below code:
Resource resourceFetch = resourceLoader.getResource("classpath:/MOResponse/UploadResponse.json"); Reader reader = new FileReader(resourceFetch.getURL().getPath());
I can only able to access the file when I run the application from eclipse. But if I try to run the project via terminal using java -jar command gives error as “java.io.FileNotFoundException: file:/home/user/Mintoak/mintoak/target/mintoak-mo-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/MOResponse/UploadResponse.json (No such file or directory)”.
Also, If I modify the code as below:
InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream("/MOResponse/UploadResponse.json"); Reader reader = new InputStreamReader(resourceAsStream);
Then its working fine while running the application using java -jar command. But now when I run application from eclipse, resourceAsStream gives null.
Please provide the solution which work in both the scenario.
Well, it’s in the name: That reads files. Literally. Files only. A resource isn’t one; it’s some compressed bytes stuck in a jar file someplace (or at least, it could be).
Your second snippet is the right answer. If it returns
null in eclipse, then your eclipse project is misconfigured. Specifically, the
resource folder should be considered a source folder too.
Well, ‘right answer’ is a bit fluid here. You’re using the right system but you’re writing it in the wrong way. The right way to read resources is
getClass().getClassLoader(). That second one breaks if you subclass, and also breaks in somewhat exotic scenarios, such as when your code is inside an agent run (because then classloader is
null to indicate you’re being loaded by the system booter).
YourClass.class.getResourceAsStream is equally simply and has strictly fewer caveats, which makes it strictly superior, which means it is the preferred style. Note that you need to prefix a
/ on your resource string if you do this (because without it, the resource string is relative to the package the class is in, which can be useful too).