tags:

views:

211

answers:

2

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?

+2  A: 

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).

Daniel Lew
+1  A: 

Use getFilesDir() to get a File at the root of your package's files/ directory.

CommonsWare