简体   繁体   中英

Load file from classpath in wildfly +java

I have a simple jsp application. I am trying to load an xml file which it there in src/xml folder. I am using below code but getting FileNotFound exception. Please let me know how to resolve this issue?

Public static void load() {
Document doc = parseDoc(Thread.currentThread().getContextClassLoader().getResource("/xml/test.xml").getFile())
}

This is throwing FileNotFound exception as the path is showing as /D:/Wildfly/bin/content/aap.war/web-inf/classes/xml/test.xml

Tried few different ways but didnt work. Please help me

Generel notes:

Please write public and not Public . "src" is not a good folder to load something. "src" normally contains your source code (aka *.java files) - which is nothing you have access to after the files are compiled and put into your server.

What I would suggest is, that you put your XML file into a jar file. So zip your xml folder and rename it to eg "xml.jar". I assume there is one folder xml/test.xml. This jar file you add to your classpath as part of your.ear or.war file. After you deploy this you can access it with:

Thread.currentThread().getContextClassLoader().getResourceAsStream("xml/text.xml");

Also don't directly read it but check for null:

InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("xml/text.xml);
if (stream == null) {
  throw new IllegalStateException("Resource 'xml/text.xml' not found on classpath");
}
//continue

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