Как создать иерархию файлов в Android '/data/data/pkg/files' 'каталог?

Я пытаюсь создать 'foo/bar.txt' в/data/data/pkg/files каталоге Android.

Это, кажется, противоречие в документах:

Для записи в файл назовите Context.openFileOutput () с именем и путем.

http://developer.android.com/guide/topics/data/data-storage.html#files

Название файла для открытия; не может содержать разделители пути.

http://developer.android.com/reference/android/content/Context.html#openFileOutput (java.lang. Строка, %20int)

И когда я звоню

this.openFileOutput("foo/bar.txt", Context.MODE_PRIVATE);

исключение выдается:

java.lang.IllegalArgumentException: File foo/bar.txt contains a path separator

Таким образом, как я создаю файл в подпапке?

8
задан Gray 16 July 2013 в 16:16
поделиться

2 ответа

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

13
ответ дан 5 December 2019 в 05:08
поделиться

Используйте getFilesDir () , чтобы получить файл в корне каталога files / вашего пакета.

7
ответ дан 5 December 2019 в 05:08
поделиться
Другие вопросы по тегам:

Похожие вопросы: