Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create files hierarchy in Androids '/data/data/pkg/files' directory?

Tags:

file

android

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?

like image 883
alex2k8 Avatar asked Dec 11 '09 16:12

alex2k8


People also ask

Where is the data folder on Android?

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.

How do I get a list of audio files in a specific folder on Android?

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.


1 Answers

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

like image 89
Dan Lew Avatar answered Sep 30 '22 14:09

Dan Lew