문제

in my app I am seeing few crashes when I try to create a directory structure under the application internal storage, such as /data/data/[pkgname]/x/y/z....

Here is the failing code:

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);
    }
}

My code is throwing the exception when trying to create the following path:

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

My manifest specifies the permission <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />, even if it should not be necessary for this purpose (it is actually necessary for my apps due to Google Maps Android API v2).

It doesn't seem to be related to the phone, since I get this exception on old phones as well as on new ones (last crash report is Nexus 4 with Android 4.3).

My guess is that the directory /data/data/my.app.pkgname doesn't exist in the first place but mkdirs() can't create it because of permissions issues, could that be possible?

Any hints?

Thanks

도움이 되었습니까?

해결책

Use getDir(String name, int mode) to create directory into internal memory. The method Retrieve, creating if needed, a new directory in which the application can place its own custom data files. You can use the returned File object to create and access files in this directory.


So example is

// 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); 

For nested directories, you should use normal java method. Like

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

So updated example should be

// 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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top