[英]Error: java.io.IOException: No such file or directory in android 11
I am trying to create a file on the file system, but I still get this exception:我试图在文件系统上创建一个文件,但我仍然得到这个异常:
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()
""
}
}
Even though I got the link after taking the photo camare:即使我在拍摄照片后获得了链接:
: /storage/emulated/0/sample-take-image/image162064003789420210510_160517.jpg : /storage/emulated/0/sample-take-image/image162064003789420210510_160517.jpg
So can someone tell me why I can't create the file in this case.所以有人可以告诉我为什么在这种情况下我不能创建文件。 I am currently on Android 11 with
我目前在Android 11上
**compileSdkVersion 30 **compileSdkVersion 30
buildToolsVersion "30.0.2"
minSdkVersion 26**
On An Android 11 device you cannot create directories or files in root of external storage.在 Android 11 设备上,您无法在外部存储的根目录中创建目录或文件。
But you can in all public directories that are already there.但是您可以在所有已经存在的公共目录中。
File(Environment.getExternalStorageDirectory(), "sample-take-image")
Replace for instance by:例如替换为:
File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "sample-take-image")
Use getExternalFilesDir(), getExternalCacheDir(), or getExternalMediaDirs() (methods on Context) instead of Environment.getExternalStorageDirectory() as this is deprecated.使用 getExternalFilesDir()、getExternalCacheDir() 或 getExternalMediaDirs()(Context 上的方法)而不是 Environment.getExternalStorageDirectory(),因为它已被弃用。
String dirPath;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
dirPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath() + "/" + getString(R.string.app_name) + "/";
} else {
dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + getString(R.string.app_name) + "/";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.