6

I'm trying to write to an output file on my HTC One and get the following message in the LogCat:

11-21 08:05:18.228: W/System.err(6609): java.lang.IllegalArgumentException: File /storage/emulated/0/com.example.pattern1/myfile.txt contains a path separator

The source code is given below:

    protected void writeToFile(String string){

    File patternDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath().toString()+"/com.example.pattern1/myfile.txt");
    patternDirectory.mkdirs();

    FileOutputStream outputStream;

    try {
      outputStream = openFileOutput(patternDirectory.getAbsolutePath().toString(), Context.MODE_APPEND);
      outputStream.write(string.getBytes());
      TextView t = (TextView)findViewById(R.id.bottomMidText);
      t.setText(patternDirectory.getAbsolutePath().toString());
      outputStream.close();

    } catch (Exception e) {
      e.printStackTrace();
    }

I would appreciate if someone can help identify the problem.

Steve Vinoski
  • 19,847
  • 3
  • 31
  • 46
Talal Saleem
  • 61
  • 1
  • 1
  • 2

2 Answers2

19

The openFileInput method will not accept path separators.('/')

it accepts only the name of the file which you want to open/access. so change the statement

outputStream = openFileOutput(patternDirectory.getAbsolutePath().toString(), Context.MODE_APPEND);

to

outputStream = new FileOutputStream (new File(patternDirectory.getAbsolutePath().toString()), true); // true will be same as Context.MODE_APPEND
Blue_Alien
  • 2,148
  • 2
  • 25
  • 29
  • 5
    Thanks for this answer. I'm not sure how I would've gotten to this answer if you had not posted it. I couldn't save to my file located in internal files directory (getFilesDir()) otherwise. I'm confused why the supposedly Google-documented way of using openFileOutput doesn't work. Very confusing of Google docs (http://developer.android.com/reference/android/content/Context.html#openFileOutput(java.lang.String, int) ). – raddevus Nov 10 '15 at 15:11
1

One problem may be the fact that you do: Environment.getExternalStorageDirectory().getAbsolutePath().toString()+"/com.example.pattern1/myfile.txt" You create a directory that has name myfile.txt