为什么从WEB-INF文件夹中加载POSModel文件不起作用?

我正在使用Spring MVC进行我的Web项目。 我将模型文件放在WEB-INF目录中

String taggerModelPath = "/WEB-INF/lib/en-pos-maxent.bin"; String chunkerModelPath = "/WEB-INF/lib/en-chunker.bin"; POSModel model = new POSModelLoader() .load(new File(servletContext.getResource(taggerModelPath).toURI().getPath())); 

这适用于Windows环境。 但是当我在远程Linux服务器上部署它时出现错误

HTTP状态500 – 请求处理失败; 嵌套exception是opennlp.tools.cmdline.TerminateToolException:POS Tagger模型文件不存在! 路径:/localhost/nlp/WEB-INF/lib/en-pos-maxent.bin

访问文件资源的最佳方法是什么? 谢谢

假设您正在使用OpenNLP 1.5.3,那么您应该使用另一种加载资源文件的方式,它不会通过URI转换使用“硬”路径引用。

给定一个环境,在WEB-INF目录中存在包含OpenNLP模型文件的另一个目录resources ,您的代码片段应该写成如下:

 String taggerModelPath = "/WEB-INF/resources/en-pos-maxent.bin"; String chunkerModelPath= "/WEB-INF/resources/en-chunker.bin"; POSModel model = new POSModelLoader().load(servletContext.getResourceAsStream(taggerModelPath)); 

请参阅Javadoc for ServletContext#getResourceAsStream和此StackOverflowpost 。

重要提示

遗憾的是,您的代码还存在其他问题。 OpenNLP类POSModelLoader仅供内部使用,请参阅POSModelLoader的官方Javadoc:

为命令行工具加载POS Tagger模型。

注意:请勿使用此类,仅供内部使用!

因此,在Web上下文中加载POSModel应该采用不同的方式:通过该类的一个可用构造函数 。 您可以重新配置上面的代码片段,如下所示:

 try { InputStream in = servletContext.getResourceAsStream(taggerModelPath); POSModel posModel; if(in != null) { posModel = new POSModel(in); // from here,  is initialized and you can start playing with it... // ... } else { // resource file not found - whatever you want to do in this case } } catch (IOException | InvalidFormatException ex) { // proper exception handling here... cause: getResourcesAsStream or OpenNLP... } 

这样,您就可以使用OpenNLP API,同时还可以进行适当的exception处理。 此外,如果模型文件的资源路径引用仍然不清楚,您现在可以使用调试器。

希望能帮助到你。