首页 > 解决方案 > 我的网络服务项目中的相对路径不起作用

问题描述

我正在创建用于在两种语言之间翻译单词的网络服务。单词在位于项目文件夹根目录的 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(系统找不到指定的文件)在

标签: javafileweb-servicessoaprelative-path

解决方案


推荐阅读