4

私のアプリでは、アプリケーションの内部ストレージ ( /data/data/[pkgname]/x/y/z....

失敗したコードは次のとおりです。

File clusterDirectory = new File(MyApplication.getContext().getFilesDir(), "store");
File baseDirectory = new File(clusterDirectory, "data");
if (!baseDirectory.exists()) {
    if (!baseDirectory.mkdirs()) {
        throw new RuntimeException("Can't create the directory: " + baseDirectory);
    }
}

次のパスを作成しようとすると、私のコードは例外をスローしています:

java.lang.RuntimeException: Can't create the directory: /data/data/my.app.pkgname/files/store/data

私のマニフェストは、<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />この目的には必要ない場合でも、パーミッションを指定しています (Google Maps Android API v2 により、実際には私のアプリには必要です)。

新しい携帯電話だけでなく古い携帯電話でもこの例外が発生するため、携帯電話とは関係がないようです (最後のクラッシュ レポートは Android 4.3 を搭載した Nexus 4 です)。

私の推測では、ディレクトリ/data/data/my.app.pkgnameはそもそも存在しませんが、 mkdirs() は権限の問題のためにディレクトリを作成できません。それは可能でしょうか?

ヒントはありますか?

ありがとう

4

1 に答える 1

5

getDir (String name, int mode)を使用して、ディレクトリを内部メモリに作成します。メソッドRetrieve は、必要に応じて、アプリケーションが独自のカスタム データ ファイルを配置できる新しいディレクトリを作成します。返された File オブジェクトを使用して、このディレクトリ内のファイルを作成およびアクセスできます。


だから例は

// Create directory into internal memory;
File mydir = context.getDir("mydir", Context.MODE_PRIVATE);
// Get a file myfile within the dir mydir.
File fileWithinMyDir = new File(mydir, "myfile"); 
// Use the stream as usual to write into the file.
FileOutputStream out = new FileOutputStream(fileWithinMyDir); 

ネストされたディレクトリの場合、通常の Java メソッドを使用する必要があります。お気に入り

new File(parentDir, "childDir").mkdir();

したがって、更新された例は

// Create directory into internal memory;
File mydir = getDir("mydir", Context.MODE_PRIVATE);

// Create sub-directory mysubdir
File mySubDir = new File(mydir, "mysubdir");
mySubDir.mkdir();

// Get a file myfile within the dir mySubDir.
File fileWithinMyDir = new File(mySubDir, "myfile"); 
// Use the stream as usual to write into the file.
FileOutputStream out = new FileOutputStream(fileWithinMyDir);
于 2013-10-01T07:56:59.810 に答える