0

我正在尝试动态写入 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) {

    }
}
4

1 回答 1

0

Better way to do this....

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();
}
于 2012-08-15T15:13:59.623 回答