我在我的Android应用程序中将数据写入xml文件。我查找了如何正确执行文件IO并发现我需要使用openFileOutput。据我所知,我的代码没有任何问题,但它一直在我在以下代码中包含try-catch的行中抛出一个异常:
public void writeSearchXML(ArrayList<String> searches, String file)
throws Exception {
// try {
// File newxmlfile = new File(file);
// newxmlfile.createNewFile();
// } catch (Exception e) {
// }
try {
// THE FOLLOWING LINE THROWS AN EXCEPTION EVERY TIME
FileOutputStream out = openFileOutput(file,
Context.MODE_WORLD_WRITEABLE);
} catch (Exception e) {
throw new Exception("Failing on fileoutput stream searches.");
}
FileOutputStream fOut = openFileOutput(file,
Context.MODE_WORLD_READABLE);
// we create a XmlSerializer in order to write xml data
XmlSerializer serializer = Xml.newSerializer();
// we set the FileOutputStream as output for the serializer, using UTF-8
// encoding
serializer.setOutput(fOut, "UTF-8");
// Write <?xml declaration with encoding (if encoding not null) and
// standalone flag (if standalone not null)
serializer.startDocument(null, Boolean.valueOf(true));
// set indentation option
serializer.setFeature(
"http://xmlpull.org/v1/doc/features.html#indent-output", true);
// start a tag called "root"
serializer.startTag(null, "searches");
for (String search : searches) {
serializer.startTag(null, "search");
serializer.text(search);
serializer.endTag(null, "search");
}
// // i indent code just to have a view similar to xml-tree
// serializer.startTag(null, "username");
// serializer.text(username);
// serializer.endTag(null, "username");
// serializer.startTag(null, "password");
// serializer.text(password);
// serializer.endTag(null, "password");
// //serializer.attribute(null, "attribute", "value");
serializer.endTag(null, "searches");
serializer.endDocument();
// write xml data into the FileOutputStream
serializer.flush();
// finally we close the file stream
fOut.close();
}
所有这些代码中唯一的问题就是这一行。我在互联网上搜索过,但我无法解决问题。我该怎么做才能解决这个问题?
更新:抛出的异常是fileNotFound
异常。这让我相信openFileOutput
函数实际上并没有像描述中那样创建文件。如何在不使用openFileOutput
的情况下在Android中创建文件?
答案 0 :(得分:0)
我在这里找到答案: android what is wrong with openFileOutput?
必须使用活动的上下文来调用openFileOutput。