代码之家  ›  专栏  ›  技术社区  ›  KrisRogo

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

  •  2
  • KrisRogo  · 技术社区  · 11 年前

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

    • 获取相对文件的URL和InputStream score.xml
    • 通过解析现有的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 是那个罐子外面的一个文件夹。

    1 回复  |  直到 11 年前
        1
  •  1
  •   mike    11 年前

    只需使用 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);
      }