且构网

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

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

更新时间:2023-01-24 12:49:39

让用户选择"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.