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

标签 java android xml nullpointerexception savechanges

我在位于 /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() 上遇到空指针异常...这就是我初始化文档文件的方式。

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

非常感谢您的帮助 公元

最佳答案

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

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 文件。

关于java - 将修改后的xml保存到Android内部存储中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43680947/

相关文章:

java - 顺序 JDBC 语句执行不进行事务处理

java - 在自动生成的 Excel 文件中添加颜色

java - FileChannel.position() 线程安全吗?

java - 为什么 Java 的 InetAddress getHostName() 没有给我主机名?

java - 如何单击图像按钮并将其显示在 Android Studio 的新页面中?

java - C++11( native 代码)与 Java(字节码)

android - 使用现有 token 的 Facebook SDK 登录

android - 创建充当我们移动网站快捷方式的 Android 应用程序

xml - 在 Scala 中编写非自结束标签 XML

java - Wrap_Content 带有服装单选按钮?