gpt4 book ai didi

java - 将 XML 保存到相对文件位置。

转载 作者:行者123 更新时间:2023-11-30 11:28:56 25 4
gpt4 key购买 nike

我有一个 writeScore.class 正在执行以下操作:

  • 获取相关文件score.xml的URL和InputStream
  • 通过解析现有的 xml 文档开始构建新的 xml 文档
  • 将新记录附加到文档生成器

程序做的最后一件事应该是将新文档写入旧文档的位置。可悲的是,我找不到任何方法来使用我已经拥有的相对路径。我尝试使用 URLConnection 而不是 .getOutputStream,但我得到了 protocol doesn't support output 错误。我还尝试了 OIUtils.copy(is, os) 将 InputStream 转换为 OutputStream 但是虽然没有错误,但由于某种原因文件没有改变并且最后修改日期指向上次我用直接文件地址做的。 (我在系统范围内进行了搜索,以防在其他地方创建了新文件,但一无所获)。

这是使用 URLConnection 方法的简化代码:

public class writeScore {

public writeScore(Score NewScore, Interface obj) {
try {

// prepare file path
URL scoreUrl = new URL("file","localhost","save/score.xml");
InputStream is = scoreUrl.openStream();
final URLConnection scoreCon = scoreUrl.openConnection();
final OutputStream os = scoreCon.getOutputStream();

// build the document
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(is);

// root element
Element root = doc.getDocumentElement();
Element rootElement = doc.getDocumentElement();

// add new save
/* removed for code cleaning */

// save source
DOMSource source = new DOMSource(doc);

// set up the transformer
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();

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

// save the file
StreamResult result = new StreamResult(os);

transformer.transform(source, result);

} // and catch all the exceptions
}
}

如果需要,我也很乐意更改我输入文件的方式,只要我可以有一个从 Java/bin/game/writeScore.class 的相对路径Java/save/score.xml 其中“Java”是我的项目目录。但是一旦游戏被打包到一个 .jar 中并且 save 是该 jar 之外的一个文件夹。

最佳答案

只需使用 new File("name") 在当前工作目录中创建一个文件。使用 new File("../name"),您可以在父目录中创建一个文件。然后,您需要将文件包装在 FileOutputStream 中。

但我会考虑使用 JAXB.unmarshal(file, clazz) 进行读取,使用 JAXB.marshal(object, file) 进行写入。在写入新文件之前,只需删除旧文件即可。我从来没有遇到过更新resp的麻烦。覆盖。

这是我的做法,我删除了异常处理和日志记录。也非常简洁和通用。

public static <T> void writeXml(T obj, File f)
{
JAXB.marshal(obj, f);
}

关于java - 将 XML 保存到相对文件位置。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18699210/

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