错误:java.io.IOException:android 11 中没有这样的文件或目录

Tha*_*ang 3 java android file kotlin android-studio

我试图在文件系统上创建一个文件,但仍然遇到此异常:

private fun getTempFolder(): File {
        val directoryFolder =
            File(Environment.getExternalStorageDirectory(), "sample-take-image")
        directoryFolder.mkdirs()
        return directoryFolder
    }
    private fun getTempFile(): File {
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHMMss", Locale.getDefault()).format(Date())
        return File(
            getTempFolder().absolutePath,
            "image".plus(Calendar.getInstance().timeInMillis).plus(timeStamp).plus(".jpg")
        )
    }
    private fun saveImageToFile(bitmap: Bitmap? = null): String? {
        return try {
            val file = getTempFile()
            Timber.e("Path: + : ${file.absolutePath}")
            file.createNewFile()
            val fOut = FileOutputStream(file)
            bitmap?.apply {
                this.compress(Bitmap.CompressFormat.JPEG, 100, fOut)
            }
            fOut.flush()
            fOut.close()
            file?.absolutePath.getDefault()
        } catch (e: Exception) {
            e.printStackTrace()
            ""
        }
    }

Run Code Online (Sandbox Code Playgroud)

尽管我在拍照后得到了链接:

:/存储/模拟/0/sample-take-image/image162064003789420210510_160517.jpg

那么有人可以告诉我为什么在这种情况下我无法创建文件。我目前 使用的是Android 11

**编译SdkVersion 30

buildToolsVersion "30.0.2"

minSdkVersion 26**
Run Code Online (Sandbox Code Playgroud)

bla*_*pps 8

在 Android 11 设备上,您无法在外部存储的根目录中创建目录或文件。

但您可以在已存在的所有公共目录中进行操作。

File(Environment.getExternalStorageDirectory(), "sample-take-image")
Run Code Online (Sandbox Code Playgroud)

例如替换为:

File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "sample-take-image")
Run Code Online (Sandbox Code Playgroud)