简体   繁体   English

正确加载打包在.war文件中的文件

[英]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 . 我有Java Web应用程序与工作jFuzzyLogic它使用库rules.fcl它位于文件WEB-INF/rules/rules.fcl

On my local server everything seems to work, but when I deploy war to Heroku, I get this error: 在我的本地服务器上,一切似乎都正常,但是当我向Heroku部署战争时,出现以下错误:

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: 在第119行的“ Results ,我试图像这样加载rules.fcl

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: 您应该使用ServletContext#getResourceAsStream它将根据war包的根级别使用设计的路径加载文件:

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: 如果有一个FIS#load方法接受InputStream作为参数,则应该像下面这样:

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 . 刚刚从该svn repo中捕获了方法签名。

Path passed to ServletContext.getRealPath() should start with a '/' character: 传递给ServletContext.getRealPath()路径应以'/'字符开头:

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

And also according to the javadoc : 并根据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). 如果servlet容器由于某种原因(例如,当从.war归档中提供内容时)无法将虚拟路径转换为真实路径,则此方法返回null

So if your .war archive is not extracted, this method won't work. 因此,如果未提取.war存档,则此方法将不起作用。 Make sure your deployed .war file gets unpacked. 确保已部署的.war文件解压缩。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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