相关文章推荐

在Android 11中,可以通过Environment.getExternalStoragePublicDirectory创建目录,但不能创建文件

0 人关注

我正在尝试用 Environment.getExternalStoragePublicDirectory 在Android 11中做一些测试。

Question 1 :为什么我不能创建一个新的文件,但我可以创建一个新的目录?
Question 2 : canRead() + canWrite() return true, but createNewFile() does not work, why?

(如果空,如果存在,......检查在本例中省略)

Get public movies dir:

fun getExternalPublicMoviesDir(): File? {
    val movies = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)
    try {
        movies.mkdirs()
        if (Environment.getExternalStorageState(movies) == Environment.MEDIA_MOUNTED) {
            return movies
    } catch (e: Exception) {
        e.printStackTrace()
    return null

创建文件/文件夹。

val externalMoviesPath = getExternalPublicMoviesDir()
externalMoviesPath.canRead() //return true
externalMoviesPath.canWrite() //return true
val newDir = File(externalMoviesPath, "newDirTest")
newDir.mkdirs() //works
val newFile = File(externalMoviesPath, "newFileTest")
newFile.createNewFile() // <- java.io.IOException: No such file or directory

Exception:

java.io.IOException: No such file or directory
    at java.io.UnixFileSystem.createFileExclusively0(Native Method)
    at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:317)
    at java.io.File.createNewFile(File.java:1008)

只是为了完整起见。在安卓10的代码中,当WRITE_EXTERNAL_STORAGE被授予时,就可以工作。