假设您使用的是 OpenNLP 1.5.3,那么您应该使用另一种加载资源文件的方法,该方法不通过 URI 转换使用“硬”路径引用。
给定一个目录中的环境WEB-INF
另一个目录resources
如果存在包含 OpenNLP 模型文件的文件,则代码片段应编写如下:
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));
请参阅 JavadocServletContext#getResourceAsStream https://docs.oracle.com/javaee/7/api/javax/servlet/ServletContext.html#getResourceAsStream-java.lang.String-和这个StackOverflow 帖子 https://stackoverflow.com/questions/1108434/howto-load-a-resource-from-web-inf-directory-of-a-web-archive.
重要提示
遗憾的是,您的代码还存在其他问题。 OpenNLP 类POSModelLoader
只为internal使用,参见官方JavadocPOS模型加载器 http://opennlp.apache.org/docs/1.5.3/apidocs/opennlp-tools/opennlp/tools/cmdline/postag/POSModelLoader.html:
为命令行工具加载 POS Tagger 模型。
Note:不要使用此类,仅供内部使用!
因此,加载一个POSModel
在 Web 上下文中应该以不同的方式完成:通过可用的方法之一该类的构造函数 http://opennlp.apache.org/docs/1.8.0/apidocs/opennlp-tools/opennlp/tools/postag/POSModel.html#POSModel(java.io.InputStream)。您可以像这样重新编写上面的代码片段:
try {
InputStream in = servletContext.getResourceAsStream(taggerModelPath);
POSModel posModel;
if(in != null) {
posModel = new POSModel(in);
// from here, <posModel> 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,同时可以进行适当的异常处理。此外,如果模型文件的资源路径引用仍不清楚,您现在可以使用调试器。
希望能帮助到你。