开发者

getResourceAsStream not loading resource

开发者 https://www.devze.com 2022-12-23 23:54 出处:网络
The project that I am currently working on utilizes an old application contained within a .jar file. One of the responsibilities of this application is that it updates the database when changes to the

The project that I am currently working on utilizes an old application contained within a .jar file. One of the responsibilities of this application is that it updates the database when changes to the configuration files are made. Every time I try to run this file (which is a simple Ant Task extension), I get an exception th开发者_如何学运维rown early in the process. I decompiled the Java file responsible, and found that the exception being thrown happens here. I do not know what the issue is, as "hibernate.cfg.xml" is contained within the same .jar file as the .class throwing the exception.

ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream in = loader.getResourceAsStream("hibernate.cfg.xml");
if (in == null) {
  throw new RuntimeException("Couldn't find built in hibernate config");
}

If anyone has any ideas, even pointing me in the right direction, I would be grateful.

Of course, any solution will have to be external, as the client already has this build of the program in production use.


Are you loading it from the root dir and you need "/hibernate.cfg.xml" instead of just hibernate.cfg.xml?


getResourceAsStream() expects the file to be in the same package as the Class that was the origin of the ClassLoader. Is your file in the right package?

Doh. Didn't read the question fully. Please ignore this.


try

InputStream in = YourClass.class..getResourceAsStream("hibernate.cfg.xml");

this will work if the class is in the same jar as the cfg file.

edit: if you can't rebuild the application, you will need to add the jar to the bootstrap classloader. this is very ugly. you can do it by running the jvm with (play with the exact arguments, you may need to add rt.jar from your jre to it as well).

-Xbootclasspath your.jar

your problem is that the code is using the classloader that loaded the Thread class, which is most likely the bootstrap classloader. and that you are now in a more complex environment (app server?) that loads your jar using a different classloader. so the bootstrap classloader can't find your resource.


It is possible that the classloader cannot open files contained in the jar file. Try one of two things 1) try extracting the jar file and running it from the file system, or 2) if the jar manifest has a ClassPath entry, try extracting the hibernate.cfg.xml into a directory in the classpath and see if it runs.


Apparently the hibernate.cfg.xml file isn't located in the source root of the JAR file, but it is instead placed inside a package. You'll need to specify the package path in the resource name as well.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号