在Android中动态更新txt文件

时间:2012-08-15 14:30:23

标签: android android-file

我正在尝试动态写入txt文件。我能够创建并写入1行文件。之后我想写第二行。在我下面的代码中,我检查文件是否存在。如果它已经存在,我写入文件而不创建新文件(见下面的代码)。但是,每当我第二次尝试写入时,我都会收到此错误。

错误:

.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) {

    }
}

1 个答案:

答案 0 :(得分: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();
}