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();
}
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+.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With