在 Android 中写入文件新的范围存储

问题描述

我已经编写了下面提到的代码来编写带有 ResponseBody 的 PDF 文件

 private fun writeResponseBodyTodisk(body: ResponseBody): Boolean {
    return try {
       val fName = "TestFile.pdf"
        val directoryName =
           context
                .getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)

        val actualFileName = File(directoryName,fName)
        if(!actualFileName.exists()){
            actualFileName.createNewFile()
        }

        var inputStream: InputStream? = null
        var outputStream: OutputStream? = null
        try {
            val fileReader = ByteArray(4096)
            var fileSizeDownloaded: Long = 0
            inputStream = body.byteStream()
            outputStream = FileOutputStream(actualFileName)
            while (true) {
                val read: Int = inputStream.read(fileReader)
                if (read == -1) {
                    break
                }
                outputStream.write(fileReader,read)
                fileSizeDownloaded += read.toLong()
            }
            ToastUtils.showShort("File Downloaded")
            outputStream.flush()
            true
        } catch (e: IOException) {
            ToastUtils.showShort("WRITE Catch Block==>"+e.message)
            false
        } finally {
            setShowLoading(false)
            if (inputStream != null) {
                inputStream.close()
            }
            if (outputStream != null) {
                outputStream.close()
            }
        }
    } catch (e: IOException) {
        ToastUtils.showShort("PDF Catch Block==>"+e.message)
        false
    }
}

每当执行上述代码时,我总是在 Catch 中得到异常。

异常:/storage/emulated/0/Android/data/com.xyz.abc.staging/files/Download/TestFile.pdf:打开失败:EISDIR(是一个目录)>

我正在 Android 11 上测试它,我必须为 Android 6 及更高版本构建此代码。但是,它在某些设备上运行良好。

解决方法

愚蠢的问题,但既然您没有对此发表任何评论,那么您的设备上是否存在 /storage/emulated/0/Android/data/com.xyz.abc.staging/files/Download/TestFile.pdf 目录?如果是这样,请将其删除并尝试再次运行您的代码。一般来说,您的代码应该适用于 Android 11。作为旁注,您应该检查 actualFileName.createNewFile() 的返回值。此外,您能否指定您的代码在其他“某些设备”上运行的 Android 版本?我还假设您已经测试了 ToastUtils,并且不会从那里抛出异常。