【问题标题】:Save XML to a relative file location.将 XML 保存到相对文件位置。
【发布时间】:2013-09-12 23:59:39
【问题描述】:

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

  • 获取 URL 和相对文件 score.xml 的 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.classJava/save/score.xml 的相对路径,其中“Java”是我的项目目录。但是,一旦游戏被打包成 .jar 并且save 是该 jar 之外的文件夹。

【问题讨论】:

    标签: java xml inputstream outputstream urlconnection


    【解决方案1】:

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

    但我会考虑使用JAXB.unmarshal(file, clazz) 阅读和JAXB.marshal(object, file) 写作。只需在编写新文件之前删除旧文件。我从来没有遇到过更新问题。覆盖。

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

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

    【讨论】:

    • 谢谢,我用新的 File 和 FileOutputStream 做到了,效果很好。下次我会去 JAXB。
    • JAXB 是 java 的一部分,它更简单而且非常标准。我真想看看。不客气!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 2013-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多