java - 我的网络服务项目中的相对路径不起作用
问题描述
我正在创建用于在两种语言之间翻译单词的网络服务。单词在位于项目文件夹根目录的 xml 文档 (dictionary.xml) 中定义。服务在绝对路径下工作得很好,但是在使用相对路径进行测试时会出现 FileNotFound 异常。
我试着只写(“字典”),它在我正在解析 xml 文件的项目中工作。
这是方法:
public String translate(String word, String lang1, String lang2) throws XPathExpressionException, FileNotFoundException {
XPathFactory factory = XPathFactory.newInstance();
XPath path = factory.newXPath();
String expression = "";
if (lang1.equals("english")) {
expression = "dictionary/word/english";
} else if (lang1.equals("spanish")) {
expression = "dictionary/word/spanish";
}
XPathExpression xPathExpression = path.compile(expression);
File xmlDocument = new File("D:\\JavaLearning\\AssignmentWebService\\Translator\\dictionary.xml");
InputSource inputSource = new InputSource(new FileInputStream(xmlDocument));
Object result = xPathExpression.evaluate(inputSource, XPathConstants.NODESET);
NodeList nodeList = (NodeList) result;
String translatedWord = "";
for (int i = 0; i < nodeList.getLength(); i++) {
if (lang1.equals("english") && word.equals(nodeList.item(i).getTextContent())) {
translatedWord = nodeList.item(i).getNextSibling().getNextSibling().getTextContent();
} else if (lang1.equals("spanish") && word.equals(nodeList.item(i).getTextContent())) {
translatedWord = nodeList.item(i).getPreviousSibling().getPreviousSibling().getTextContent();
}
}
if (translatedWord.equals("")) {
translatedWord = "Word \"" + word + "\" doesn't exist in our database!";
}
return translatedWord;
}
错误:引起:service.FileNotFoundException_Exception:dictionary.xml(系统找不到指定的文件)在
解决方案
推荐阅读
- webstorm - JetBrains WebStorm - 设置调试控制台以显示快捷方式/超链接
- dart - 在 Dart 中组合期货流
- sql - 你如何连接 substr 函数?
- php - if条件如何从函数php返回值
- c# - 无法在 c#view 中将 Json 子项日期时间与当前日期时间进行比较
- r - R中的向量索引
- python - 是否可以将一个 QGraphicsPixmapItem 附加到另一个?
- ruby-on-rails - 按钮下载电子邮件中的附件
- haskell - Haskell - 延迟评估是否会导致此文件夹停止评估所有功能
- class - C ++:在基类中定义的静态向量在main中失去了它的价值