我正在开发一个 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)
}
Run Code Online (Sandbox Code Playgroud)
我响应文件选择的功能:
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 …Run Code Online (Sandbox Code Playgroud) 我正在开发一个应用程序,我希望能够在该应用程序的.txt文件中导出和导入一些数据。该应用程序的最低API为21。
导出部分效果很好,但是导入部分遇到了麻烦。
我打开文件资源管理器:
butImportPatient.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("*/*");
startActivityForResult(intent, IMPORTPATIENT_ACTIVITY_REQUEST_CODE);
}
});
Run Code Online (Sandbox Code Playgroud)
这看起来像在工作。
但是我的onActivityResult不起作用,我没有找到如何从Uri获取文件。
现在,这是我的代码:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == IMPORTPATIENT_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
File file = new File(data.getData().getPath()) ;
String path = file.getAbsolutePath() ;
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(path));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append("\n"); …Run Code Online (Sandbox Code Playgroud)