2012-08-15 70 views
0

我正試圖動態地寫入一個txt文件。我能夠創建並寫入文件1行。之後我想寫第二行。在我的代碼下面我檢查文件是否存在。如果它已經存在,我會寫入文件而不創建新文件(請參見下面的代碼)。但是,無論何時我嘗試第二次寫入,我都會收到此錯誤。在Android中動態更新txt文件

錯誤:

.IllegalArgumentException: File //sdcard//uiu_error_report.txt contains a path separator 

代碼:

String filename = "/sdcard/uiu_error_report.txt"; 

File myFile = new File(filename); 

if (myFile.createNewFile()) { 

    FileOutputStream fOut = new FileOutputStream(myFile); 
    OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); 
    myOutWriter.append("[" + dateFormatted + "," + module2 + "," + type2 + "," + message2 + "]"); 
    myOutWriter.close(); 
    fOut.close(); 

} else { 

    try { 
     OutputStreamWriter out = new OutputStreamWriter(context.openFileOutput(filename,countFileRows()+1)); 
     // write the contents on mySettings to the file 
     out.write("[" + dateFormatted + "," + module2 + "," + type2 + "," + message2 + "]"); 
     // close the file 
     out.close(); 

    // Do something if an IOException occurs. 
    } catch (java.io.IOException e) { 

    } 
} 
+0

也許看到這一點:http://stackoverflow.com/questions/5963535/java-lang-illegalargumentexception-contains-a-path-separator – 2012-08-15 14:33:18

回答

0

更好的辦法做到這一點....

try { 
    FileOutputStream fos = context.openFileOutput(filename, Context.MODE_APPEND | Context.MODE_WORLD_READABLE); 
    OutputStreamWriter myOutWriter = new OutputStreamWriter(fos); 
    myOutWriter.append("[" + dateFormatted + "," + module2 + "," + type2 + "," + message2 + "]"+"/n"); 
    // myOutWriter.close(); 

    myOutWriter.close(); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 
+0

不建議捕獲異常。你應該找出具體的錯誤。 – Zorayr 2013-06-12 01:27:18