GetResourceAsStream does not load a resource

The project I'm working on is using an old application contained in a .jar file. One of the responsibilities of this application is that it updates the database when changes are made to the configuration files. Every time I try to run this file (which is a simple Ant Task extension), I get an exception thrown at the beginning of the process. I decompiled the responsible Java file and found that an exception was thrown here. I do not know what the problem is, because "hibernate.cfg.xml" is contained in the same .jar file as .class, throwing an 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 ideas, even pointing me in the right direction, I would be grateful.

Of course, any solution should be external, since the client already has this program assembly in the production process.

+3
source share
5 answers

Do you download it from the root directory and you need "/hibernate.cfg.xml" instead of just hibernate.cfg.xml?

+3
source

getResourceAsStream () expects the file to be in the same package as the class that was the source of ClassLoader. Is your file in the correct package?

Doh. Did not read the question completely. Please ignore this.

+2
source

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

, , cfg.

, bootstrap. . , jvm ( , rt.jar jre ).

-Xbootclasspath your.jar

, , Thread, , , bootstrap. ( ?), . bootstrap .

+1

It is possible that the class loader cannot open the files contained in the jar file. Try one of two things: 1) try to extract the jar file and run it from the file system, or 2) if the jar manifest has a ClassPath entry, try extracting hibernate.cfg.xml to the directory in the class path and see if it works.

0
source

Apparently, the file is hibernate.cfg.xmlnot located in the source root of the JAR file, but it is placed inside the package. You also need to specify the directory path in the resource name.

0
source

Source: https://habr.com/ru/post/1738062/


All Articles