【发布时间】:2020-03-26 03:15:34
【问题描述】:
我正在开发一个 Android 应用程序,其中一个功能是让用户选择要打开的文件(我想打开一个纯文本 .txt 文件)。我之前使用 Java 开发过 Android 应用程序,但对于这个应用程序,我使用的是 Kotlin,这是我第一次使用 Kotlin。
我目前让应用程序显示一个文件选择器,让用户点击他们想要打开的文件。然后我尝试使用 File 对象打开文件并执行 forEachLine 循环。但由于某种原因,它会抛出一个 java.io.FileNotFoundException(没有这样的文件或目录)以及从文件选择器中选择的文件。不知道出了什么问题,如果我必须做一些转换来转换文件路径?
我的“加载”按钮的代码:
val btn_load: Button = findViewById<Button>(R.id.btn_load_puzzle)
btn_load.setOnClickListener {
val intent = Intent()
.setType("*/*")
.setAction(Intent.ACTION_GET_CONTENT)
startActivityForResult(Intent.createChooser(intent, "Select a file"), 111)
}
我响应文件选择的函数:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// Selected a file to load
if ((requestCode == 111) && (resultCode == RESULT_OK)) {
val selectedFilename = data?.data //The uri with the location of the file
if (selectedFilename != null) {
val filenameURIStr = selectedFilename.toString()
if (filenameURIStr.endsWith(".txt", true)) {
val msg = "Chosen file: " + filenameURIStr
val toast = Toast.makeText(applicationContext, msg, Toast.LENGTH_SHORT)
toast.show()
File(selectedFilename.getPath()).forEachLine {
val toast = Toast.makeText(applicationContext, it, Toast.LENGTH_SHORT)
toast.show()
}
}
else {
val msg = "The chosen file is not a .txt file!"
val toast = Toast.makeText(applicationContext, msg, Toast.LENGTH_LONG)
toast.show()
}
}
else {
val msg = "Null filename data received!"
val toast = Toast.makeText(applicationContext, msg, Toast.LENGTH_LONG)
toast.show()
}
}
}
在创建 File 对象以执行 forEachLine 循环的行上引发 FileNotFound 异常:
java.lang.RuntimeException: 传递结果失败 ResultInfo{who=null, request=111, result=-1, data=Intent { dat=content://com.android.externalstorage.documents/document/0000-0000 :Sudoku puzzles/hard001.txt flg=0x1 }} 到活动 {com.example.sudokusolver/com.example.sudokusolver.MainActivity}: java.io.FileNotFoundException: /document/0000-0000:Sudoku puzzles/hard001.txt (没有这样的文件或目录)
【问题讨论】:
标签: android file exception kotlin filenotfoundexception