且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 SAF(存储访问框架)的 Android SD 卡写入权限

更新时间:2023-01-24 12:53:59

让用户选择SD 卡"甚至内部存储" SAF 根目录可以让您的应用程序访问相应的存储,但只能通过 SAF API,而不是直接通过文件系统.例如你的代码可以被翻译成类似的东西:

Letting the user choose the "SD card" or even the "Internal storage" SAF root give your application access to the corresponding storage, but only through the SAF API, not directly via the filesystem. For example you code could be translated into something like :

public void writeFile(DocumentFile pickedDir) {
    try {
        DocumentFile file = pickedDir.createFile("image/jpeg", "try2.jpg");
        OutputStream out = getContentResolver().openOutputStream(file.getUri());
        try {

            // write the image content

        } finally {
            out.close();
        }

    } catch (IOException e) {
        throw new RuntimeException("Something went wrong : " + e.getMessage(), e);
    }
}

在最新版本的 Android 中,几乎完全不推荐使用 java.io.File 访问应用程序外部的数据.

In recent version of Android, accessing data outside your application using java.io.File is almost completely deprecated.