我需要在Android应用中创建一个文本文件,但它不允许我这样做。验证它已被创建的方法使我返回伪造品。我该怎么办?
我已经为应用程序manifest.xml分配了写许可权,但是它对我也不起作用。 我还提出了权限请求。
我分配给manifest.xml的权限是这样的:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
写文件的代码,我是这样写的:
fun writeFile() {
if (ContextCompat.checkSelfPermission(this@GenerateCodeActivity,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE),
PackageManager.PERMISSION_GRANTED)
}
val sd_main = File(Environment.getExternalStorageDirectory().absolutePath+"/FilesMyApp")
var success = true
if (!sd_main.exists()) {
success = sd_main.mkdir()
}
if (success) {
val sd = File("${this@GenerateCodeActivity.auth.currentUser?.uid}")
val hola = "HOLA QUE TAL"
if (!sd.exists()) {
success = sd.mkdir()
}
if (success) {
// directory exists or already created
val dest = File(sd, "${this@GenerateCodeActivity.auth.currentUser?.uid}.txt")
try {
// response is the data written to file
FileOutputStream(dest).use { it.write(hola.toByteArray()) }
} catch (e: Exception) {
// handle the exception
}
} else {
// directory creation is not successful
}
}
}
我想输入指示的文本字符串,但不允许我输入“ if(成功)”区域。
答案 0 :(得分:0)
val sd = File("${this@GenerateCodeActivity.auth.currentUser?.uid}")
您尚未指定目录。使用:
val sd = File(sd_main, "${this@GenerateCodeActivity.auth.currentUser?.uid}")