如何创建文件夹(Android R - Api 30)?

问题描述 投票:0回答:4

读到 Android 11 有范围存储,但我找不到任何信息,如何在

/storage/emulated/0/
中创建和使用文件夹?旧方法仅适用于 api 29 及以下 :(

android android-file android-storage android-11
4个回答
10
投票

自 Android Q 以来,我们可以在应用程序特定存储中创建文件夹。它的路径:

Android->data->package name->files->your folder

使用这个:

File file;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
    file = new File (this.getExternalFilesDir(null) + path);
} else {
    file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + path);
}

if (!file.exists()) {
    file.mkdirs();
}

5
投票

在 Android 11 上,Android 10 中关于访问外部存储的限制要少得多。

Environment.getExternalStorageDirectory()

再次可读并且

Environment.getExternalStoragePublicDirectory(...)

对于

Environment.DIRECTORY_DOCUMENTS
等文件夹是可写的。

Android 操作系统非常挑剔,在大多数目录中为您的文件使用正确的扩展名。


0
投票

如果有人需要这段代码,我正在扩展接受的答案:

请注意,我在这里创建了两个文件,第一个是文件将要写入的目录,第二个是文件本身。您必须检查目录是否存在并创建它,否则将抛出 FileNotFoundException。

File videoFile;
File videoDir;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
    //Android 11+
    videoDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), File.separator + "YOUR_DIRECTORY_NAME");
    videoFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), "/YOUR_DIRECTORY_NAME/" + videoName);
} else {
    //Old Android version
    videoDir = new File(Environment.getExternalStorageDirectory(), Environment.DIRECTORY_MOVIES + File.separator + "YOUR_DIRECTORY_NAME");
    videoFile = new File(Environment.getExternalStorageDirectory(), Environment.DIRECTORY_MOVIES + File.separator + "YOUR_DIRECTORY_NAME" + File.separator + videoName);
}
if(!videoDir.exists()) {
    if(!videoDir.mkdir()) {
        infoSB("No Storage Permission");
        return;
    }
}
try {
    if(!videoFile.exists()) {
        FileOutputStream fos = new FileOutputStream(videoFile);
        fos.write(response);
        fos.close();
    }
} catch (IOException e) {}
                    

-2
投票

第一步:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

第二步:

Environment.getExternalStorageDirectory().absolutePath + "/your_folder_name"
© www.soinside.com 2019 - 2024. All rights reserved.