将修改后的xml保存到Android内部存储中

问题描述 投票:0回答:1

我在位于/data/data.my.package.app/files/file.xml的现有xml文件中添加了节点,我只想保存文件,但我没有发现。

我试过在另一篇文章中看到的这个功能:

private void save(Document newDoc) throws Exception{
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    StreamResult result = new StreamResult(new File(context.getFilesDir().getAbsolutePath() + "/file.xml"));
    Source source = new DOMSource(newDoc);
    transformer.transform(source, result);
}

但是我在tranformer.transform()上得到一个空指针异常......这就是我初始化我的Document文件的方法。

FileInputStream is = new FileInputStream(context.getFilesDir().getAbsolutePath() + "/file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);

非常感谢你帮助A.D.

java android xml nullpointerexception savechanges
1个回答
1
投票

该文件不能是新的。必须已经存在:

StreamResult result = 
     new StreamResult(new File(context.getFilesDir().getAbsolutePath() +   "/file.xml"));

对我来说这项工作:

//save the doc as string  in a text file with the same name (extension   .xml)
save(this, body, dir, FILENAME_XML);

//apply the transformer
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory_p.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(
    new File(dir+File.separator+FILENAME_XML));
transformer.transform(source, result);

生成文件xml。

© www.soinside.com 2019 - 2024. All rights reserved.