openFileOutput throws exception
I am writing data to xml files in my android app. I looked up how to properly do file IO and found that I need to use openFileOutput. As far as I can tell there is nothing wrong with my code but it keeps throwing an exception at the line I have a try-catch wrapped around in the following code:
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(); }
The only problem in all this code is just that one line. I've searched all over the internet and I haven't been able to fine a solution. What can I do to fix this?
UPDATE: The exception being thrown is a fileNotFound exception. This leads me to believe that the openFileOutput function doesn't actually create the file like it says it does in the description. What can I do in Android to create the file without using openFileOutput?
Answers
I found the answer here: android what is wrong with openFileOutput ?
openFileOutput has to be called using an activity's context.