Loading a non java file from jar
Scenario: You have a configuration or text or any other non java file of that kind. You have to package your application(apis) as jar(executable or non executable) for the client to use. However if the non java files used by your application are static(cannot change at runtime or by the user), you might want to package them as part of your archive. Here is the code to do exactly that:
public static InputStream loadFileFromJar(String fName){
return Constants.class.getClassLoader().getResourceAsStream(fName);
}
We all know that getResourceAsStream() method of ClassLoader will load any file from available classpath. However in case of jar(some times) the classloader could be different. So we play a small trick: We first load a class(could be even a dummy blank class) from the jar and acquire the handle to that classloader. Now we can be assured that this classloader will have access to all the resources inside the jar.
One more thing: You should keep your file either in base of the jar or in a relative folder.
Labels: classloader, jar, java, loading a file from jar
0 Comments:
Post a Comment
<< Home