[英]Why does the loading of a POSModel file not work from inside the WEB-INF folder?
我將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-請求處理失敗; 嵌套的異常是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));
有關ServletContext#getResourceAsStream的信息 ,請參見Javadoc;有關StackOverflow的信息,請參見。
重要提示
可悲的是,您的代碼還有其他問題。 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, <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的要求,同時可以進行適當的異常處理。 而且,如果模型文件的資源路徑引用仍然不清楚,您現在可以使用調試器。
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.