应用程序内部存储器上的mkdirs()在Android上失败

Ven*_*r85 3 android android-file

在我的应用程序中,当我尝试在应用程序内部存储下创建目录结构时,我看到很少崩溃,例如/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);
    }
}
Run Code Online (Sandbox Code Playgroud)

尝试创建以下路径时,我的代码抛出了异常:

java.lang.RuntimeException: Can't create the directory: /data/data/my.app.pkgname/files/store/data
Run Code Online (Sandbox Code Playgroud)

我的清单指定了权限<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />,即使它不需要用于此目的(由于Google Maps Android API v2,我的应用程序实际上是必需的).

它似乎与手机没有关系,因为我在旧手机和新手机上都有这个例外(最新的崩溃报告是Nexus 4和Android 4.3).

我的猜测是该目录/data/data/my.app.pkgname首先不存在,但由于权限问题,mkdirs()无法创建它,这可能吗?

任何提示?

谢谢

Pan*_*mar 5

使用getDir(String name,int mode)将目录创建到内部存储器中.方法检索,创建需要的新目录,应用程序可以在其中放置自己的自定义数据文件.您可以使用返回的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); 
Run Code Online (Sandbox Code Playgroud)

对于嵌套目录,您应该使用普通的java方法.喜欢

new File(parentDir, "childDir").mkdir();
Run Code Online (Sandbox Code Playgroud)

所以更新的例子应该是

// 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);
Run Code Online (Sandbox Code Playgroud)