0

I am trying to write into a txt file dynamically. I am able to create and write into a file 1 line. After that I want to write a second line. In my code below I check if the file exist. If it exist already I write into the file without creating a new one (see below code). However I am getting this error whenever I try and write for the second time.

Error:

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

Code:

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

    }
}
Zorayr
  • 23,770
  • 8
  • 136
  • 129
user182192
  • 729
  • 3
  • 14
  • 26
  • Maybe see this : http://stackoverflow.com/questions/5963535/java-lang-illegalargumentexception-contains-a-path-separator – Alexis C. Aug 15 '12 at 14:33

1 Answers1

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();
}
Zorayr
  • 23,770
  • 8
  • 136
  • 129
user182192
  • 729
  • 3
  • 14
  • 26