简体   繁体   中英

getResourceAsStream not loading resource

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 thrown 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.

你是从root目录加载它,你需要“/hibernate.cfg.xml”而不只是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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM