2014-04-23 57 views
1

我有一段代碼不能按我的需要工作。Android - 寫入文件時出錯

deleteFile(mealFile); 
    //TODO: Error 
    try{ 
     FileOutputStream fos = openFileOutput(mealFile, MODE_APPEND); 
     OutputStreamWriter osw = new OutputStreamWriter(fos); 
     for(int i=0; i<temp_name.size(); i++){ 
      if(!(temp_name.get(i).equals(mealName.getText().toString()))){ 
       osw.append(temp_name.get(i) + "\t"); 
       osw.append(temp_meals.get(i) + "\t"); 
       osw.append(temp_scale.get(i) + "\t"); 
       System.getProperty("line.separator"); 
      } 
     } 
    }catch(Exception e){ 
     updateWarningMessage(6); 
    } 

必須有一些明顯的我錯過了。此代碼不想將任何內容追加到文件中。我知道代碼沒有失敗(沒有例外),我知道我嘗試追加的ArrayLists不是空的並且包含字符串(我甚至用「osw.append(」test「);」沒有運氣)嘗試過。我知道for循環的運行次數與它應有的次數相同,正如我所說的,我知道「if」在起作用。起初,我雖然是在刪除文件或延遲,但我嘗試添加一個方法,直接在DeleteFile()之後將文本寫入該文件,並且這部分工作正常。而且,此代碼不會追加任何內容。

有沒有人有任何線索可能是什麼錯?我完全失去了,另一種方法我使用附加看起來有點相同。我現在要嘗試將ArrayLists傳遞給一個新的方法,並嘗試從那裏添加它,但我不喜歡讓這種奇怪的行爲沒有解決。我希望我只是錯過了整天編碼的一些事情。任何人都能發現任何東西嗎

回答

0

我會flush()每次迭代和close()流完的時候,因爲這是後處理文件時通常的過程。

try{ 
     FileOutputStream fos = openFileOutput(mealFile, MODE_APPEND); 
     OutputStreamWriter osw = new OutputStreamWriter(fos); 
     for(int i=0; i<temp_name.size(); i++){ 
      if(!(temp_name.get(i).equals(mealName.getText().toString()))){ 
       osw.append(temp_name.get(i) + "\t"); 
       osw.append(temp_meals.get(i) + "\t"); 
       osw.append(temp_scale.get(i) + "\t"); 
       System.getProperty("line.separator"); 
       osw.flush(); 
      } 
     } 
     osw.close(); 
    }catch(Exception e){ 
     updateWarningMessage(6); 
    } 
+0

耶,這個作品!猜猜我不得不查看這兩個實際上做了什麼。所以它寫入文件的flush,而不是append?我可以自己看看這個,謝謝:) – mathkid91

+0

你有正確的想法。直到flush()或close()被調用('close()'調用flush()'然後*實際*關閉流,這也是非常重要的)。 –

0

這可能是因爲在你的清單,你忘了寫添加到外部存儲

解決方案:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
+0

這是A-Cs的建議,是我的失誤,但非常感謝您的回覆反正:) – mathkid91