gpt4 book ai didi

java - 在 Java 中编写 XML FileNotFoundException

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:02:36 26 4
gpt4 key购买 nike

我遇到了以下代码的一些问题

       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

最佳答案

我设法解决了这个问题。

这里是错误:

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);

...

关于java - 在 Java 中编写 XML FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15324008/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com