简体   繁体   中英

Using resources inside a jar from war module

I'm having a jar file say toolkit.jar which contains resource files under com.project.resources. When I tested independently I can read those resources with Class.getResource . But when I used the jar file in war module (web service), getResource always returns null. How can I access those resource file?

com/project/resources/ contains arial.ttf
com/project/toolkit/ contains ToolKit.java

renderer is ITextRenderer object.

renderer.getFontResolver().addFont(this.getClass().getResource("../resources/arial.ttf").
    toString(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

And this toolkit.jar is using in a web service.

Use getResourceAsStream() instead of getResource

InputStream in =
new InputStreamReader(FileLoader.class.getClassLoader().getResourceAsStream("file.txt") );

If its doesn't work

The best way to look to a config file from a webapp is to implement the servlet method init(). Let' try using the same code

InputStream in =
new InputStreamReader(FileLoaderServlet.class.getClassLoader().getResourceAsStream("file.txt") );

Refer https://haveacafe.wordpress.com/2008/10/19/how-to-read-a-file-from-jar-and-war-files-java-and-webapp-archive/

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