在Java FileNotFoundException中编写XML

时间:2013-03-10 15:38:20

标签: java xml

我面临以下代码的问题

       try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

            //root elements
            Document doc = docBuilder.newDocument();

            Element rootElement = doc.createElement("subcompany");
            doc.appendChild(rootElement);

            //id elements
            Element id = doc.createElement("id");
            id.appendChild(doc.createTextNode(subCompanyId != null ? subCompanyId : " "));
            rootElement.appendChild(id);

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);

            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

            String xmlPath = "/project/MallDirectory/mall";

            //EDITED for File creation before writing.
            boolean isFileCreated = new File(xmlPath, "subcompany.xml").createNewFile();
            System.out.println(isFileCreated);                

            StreamResult result = new StreamResult(new File(xmlPath, "subcompany.xml"));

            transformer.transform(source, result);

        } catch (Exception ex) {
            ex.printStackTrace();
        }

运行后,我收到以下错误:

javax.xml.transform.TransformerException: java.io.FileNotFoundException: file:/project/MallDirectory/mall/subcompany.xml (No such file or directory)

它曾用于我的其他项目,但不是这一次。这到底出了什么问题?

编辑:

这是我想写的路径。文件已创建,但它是空的。

enter image description here

4 个答案:

答案 0 :(得分:20)

我设法解决了这个问题。

这是错误:

javax.xml.transform.TransformerException: java.io.FileNotFoundException: file:/project/MallDirectory/mall/subcompany.xml (No such file or directory)

我想也许变换器正在尝试将xml写入此路径'file:/project/MallDirectory/mall/subcompany.xml'。我不知道它是怎么发生的,因为我专门设置了文件路径'/project/MallDirectory/mall/subcompany.xml',并且没有以'file:/'作为前缀。

因此,我以某种方式设法通过这样做来解决它:

...

//ERROR CODE:
//StreamResult result = new StreamResult(new File(xmlPath, "subcompany.xml"));
//
StreamResult result = new StreamResult(new File(xmlPath, "subcompany.xml").getPath());
transformer.transform(source, result);

...

答案 1 :(得分:0)

在任何时间点处于打开状态的文件数量都是特定于操作系统(可以配置),并且已经达到了上限。请查看应用程序的代码库中的内容。你有一些代码试图打开一个文件,但在使用后没有关闭流。检查这些代码。

答案 2 :(得分:0)

您定义的目录路径不正确。查看JavaDoc以确定到达文件位置所需的目录路径形式。

JavaDoc java.io.File

答案 3 :(得分:0)

如果“/ project”是您的项目名称,请尝试“./MallDirectory/mall”,否则请尝试“./project/MallDirectory/mall”。请仔细观察它包含点的字符串。