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.
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?
Use
getFilesDir()
to get aFile
at the root of your package'sfiles/
directory.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():
getFilesDir()
always returns the directory "files". AndmakeFilename()
?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).To write to a file in a subfolder of internal storage you will need to create the file (and subfolder if not already there) first, then create the FileOutputStream object.
Here is the method I used
Assuming the original post sought how to both create a subdirectory in the files area and write a file in it, this might be new in the docs:
Since: API Level 1
You can add files with path in private directory like that