Java – classloader loads the wrong file
I use this snippet to get the file as the input stream File version Txt is packaged in the jar of my application, which is located in the top folder
InputStream resource = getClass().getClassLoader().getResourceAsStream("version.txt");
This works almost all the time But for a user, it is picking up another version Txt, this is not in my jar How do I ensure that a specific version. In my jar is loaded Txt file?
Solution
When you say "top folder", do you mean the default package? If this is the case, you must ensure that the jar is on the classpath than in other versions Txt file, because Java searches the classpath until it finds the first match
Because it's hard to ensure that your jar is always the first, you should change version Txt files are placed in non default packages, for example:
com.yourcompany.yourproject.version
Then you need to modify the code to find it:
Stream resource = getClass().getClassLoader().getResourceAsStream("com/yourcompany/yourproject/version/version.txt");
Using the default package is anti - pattern