简体   繁体   中英

Properly load file packaged inside .war file

I have Java Web application that works with jFuzzyLogic library which uses rules.fcl file which is located at WEB-INF/rules/rules.fcl .

On my local server everything seems to work, but when I deploy war to Heroku, I get this error:

java.lang.NullPointerException
java.io.FileInputStream.<init>(FileInputStream.java:133)
java.io.FileInputStream.<init>(FileInputStream.java:96)
java.io.FileReader.<init>(FileReader.java:58)
net.sourceforge.jFuzzyLogic.FIS.load(FIS.java:143)
net.sourceforge.jFuzzyLogic.FIS.load(FIS.java:130)
com.vukstankovic.professionalorientation.Results.calculation(Results.java:119)

At my Results at line 119 I'm trying to load rules.fcl like this:

FIS fis = FIS.load(ctx.getRealPath("WEB-INF/rules/rules.fcl"));

At the begining of this method I have this annotation:

@Context ServletContext ctx;

What am I doing wrong?

You should be using ServletContext#getResourceAsStream which would load your files with designed path based on root level of war package:

InputStream inputStream = ctx.getResourceAsStream("/WEB-INF/rules/rules.fcl");

Then, it is up to you to use that stream and chain it to load your file content. It should be something like the follwoing if there a FIS#load method that accept InputStream as paramter:

boolean verbose = true; //Just choose your suitable value (verbose mode or not)
FIS fis = FIS.load(inputStream, verbose);

Just caught the method signature from this svn repo .

Path passed to ServletContext.getRealPath() should start with a '/' character:

FIS fis = FIS.load(ctx.getRealPath("/WEB-INF/rules/rules.fcl"));

And also according to the javadoc :

This method returns null if the servlet container cannot translate the virtual path to a real path for any reason (such as when the content is being made available from a .war archive).

So if your .war archive is not extracted, this method won't work. Make sure your deployed .war file gets unpacked.

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