2010-12-01 150 views
1

我正在向我的android應用中的xml文件寫入數據。我查了一下如何正確地做文件IO,發現我需要使用openFileOutput。據我可以告訴有什麼錯我的代碼,但它一直在該行拋出一個例外,我有一個try-catch下面的代碼纏:openFileOutput引發異常

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函數實際上並不像它在說明中所說的那樣創建文件。如何在Android中創建文件而不使用openFileOutput

+0

請您提供錯誤日誌。哪一行是麻煩的? – 2010-12-01 07:25:54

回答