I try to create 'foo/bar.txt' in Android's /data/data/pkg/files directory.
It seems to be a contradiction in docs:
To write to a file, call Context.openFileOutput() with the name and path.
http://developer.android.com/guide/topics/data/data-storage.html#files
The name of the file to open; can not contain path separators.
http://developer.android.com/reference/android/content/Context.html#openFileOutput(java.lang.String,%20int)
And when I call
this.openFileOutput("foo/bar.txt", Context.MODE_PRIVATE);
exception is thrown:
java.lang.IllegalArgumentException: File foo/bar.txt contains a path separator
So how do I create file in subfolder?
Please go to Android system settings, find storage section, click it. From the storage page, find "Files" item, and click it. If there are multiple file managers to open it, please make sure to choose "Open with Files" to open it, which is the system file manager app.
id. mylist); myList = new ArrayList<String>(); File directory = Environment. getExternalStorageDirectory(); file = new File( directory + "/Test" ); File list[] = file. listFiles(); for( int i=0; i< list.
It does appear you've come across a documentation issue. Things don't look any better if you dig into the source code for ApplicationContext.java. Inside of openFileOutput():
File f = makeFilename(getFilesDir(), name);
getFilesDir()
always returns the directory "files". And makeFilename()
?
private File makeFilename(File base, String name) {
if (name.indexOf(File.separatorChar) < 0) {
return new File(base, name);
}
throw new IllegalArgumentException(
"File " + name + " contains a path separator");
}
So by using openFileOutput()
you won't be able to control the containing directory; it'll always end up in the "files" directory.
There is, however, nothing stopping you from creating files on your own in your package directory, using File and FileUtils. It just means you'll miss out on the conveniences that using openFileOutput()
gives you (such as automatically setting permissions).
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