4

I want save a file in internal folder, but get this error:

Error: file contains a path separator

Here's my code:

try {
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("storage/emulated/0/test2/test2.txt", Context.MODE_APPEND));
    outputStreamWriter.append(data);
    outputStreamWriter.close();
}
CAMOBAP
  • 5,523
  • 8
  • 58
  • 93
pepito_01
  • 111
  • 3
  • 10
  • See this answer: http://stackoverflow.com/a/29263819/166339 – Asaph Sep 04 '16 at 17:38
  • Possible duplicate of [android what is wrong with openFileOutput?](http://stackoverflow.com/questions/3625837/android-what-is-wrong-with-openfileoutput) – Sam Bellerose Sep 04 '16 at 17:40

1 Answers1

13

First, openFileOutput() only takes a filename, not a full path. Quoting the documentation for the first parameter to openFileOutput(): "The name of the file to open; can not contain path separators.".

Second, openFileOutput() is for files on internal storage. Based on your path, you appear to be trying to work with external storage. You cannot use openFileOutput() for that.

Third, never hardcode paths. Your path is wrong for hundreds of millions of Android devices. Always use Android-provided methods to derive directories to use.

Fourth, do not clutter up the root of external storage with new directories. That is equivalent to putting all your program's files in the root of the C: drive on Windows.

Fifth, writing to a location in the root of external storage means that the user has to grant you rights to write anywhere on external storage (via the WRITE_EXTERNAL_STORAGE permission) which also adds complexity to your app (courtesy of runtime permissions on Android 6.0+).

So, for example, you could replace your first line with:

OutputStreamWriter outputStreamWriter =
    new OutputStreamWriter(new FileOutputStream(new File(getExternalFilesDir(null), "test2.txt")));

This gives you a location on external storage (getExternalFilesDir()) that is unique for your app and does not require any special permission on Android 4.4+.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491