我试图在文件系统上创建一个文件,但仍然出现以下异常:
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()
""
}
}
即使我在拍照后得到了链接:
: /storage/emulated/0/sample-take-image/image162064003789420210510_160517.jpg
但为什么我不能在这种情况下创建文件呢,请问有谁知道原因吗?我目前使用的是Android 11和compileSdkVersion 30。
buildToolsVersion "30.0.2"
minSdkVersion 26**
directoryFolder.mkdirs()
Bad coding. Better:if ( ! directoryFoldes.exists() if ( !directoryFolder.mkdirs()) return;
- blackapps