Android - 从 Intent Chooser 打开 txt 文件
Android - open txt file from Intent Chooser
通过点击某个按钮 - 创建了 selecting txt 文件的意图:
Intent intent = new Intent()
.setType("text/plain")
.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select a TXT file"), 123);
它工作正常 - 我 select 来自 phone 内部存储器根文件夹的 txt 文件 --- /storage/emulated/0/kote.txt
但是当我尝试从中读取数据时,我得到 FileNotFoundException:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if(requestCode==123 && resultCode==RESULT_OK) {
Uri selectedfile_uri = intent.getData();
Log.e("TAG7", "selectedfile_uri --- " + selectedfile_uri );
File myFile_test1 = new File(selectedfile_uri.getPath());
Log.e("TAG7", myFile_test1.getPath() + " .exists() "+myFile_test1.exists());
File myFile_test2 = new File(selectedfile_uri.getEncodedPath());
Log.e("TAG7", myFile_test2.getPath() + " .exists() "+myFile_test2.exists());
function_read_txt_file(myFile_test1); //returns FileNotFoundException
function_read_txt_file(myFile_test2); //returns FileNotFoundException
}
}
logcat:
E/TAG7: selectedfile_uri --- content://com.android.externalstorage.documents/document/primary%3Akote.txt
E/TAG7: /document/primary:kote.txt .exists() false
E/TAG7: /document/primary%3Akote.txt .exists() false
E/TAG7: FileNotFoundException
我在这里缺少什么?干杯
Uri
可能没有您文件的直接访问路径。您应该通过从 Uri
打开 InputStream
来打开文件
Uri selectedfile_uri = intent.getData();
InputStream inputStream = getContentResolver().openInputStream()
通过点击某个按钮 - 创建了 selecting txt 文件的意图:
Intent intent = new Intent()
.setType("text/plain")
.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select a TXT file"), 123);
它工作正常 - 我 select 来自 phone 内部存储器根文件夹的 txt 文件 --- /storage/emulated/0/kote.txt
但是当我尝试从中读取数据时,我得到 FileNotFoundException:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if(requestCode==123 && resultCode==RESULT_OK) {
Uri selectedfile_uri = intent.getData();
Log.e("TAG7", "selectedfile_uri --- " + selectedfile_uri );
File myFile_test1 = new File(selectedfile_uri.getPath());
Log.e("TAG7", myFile_test1.getPath() + " .exists() "+myFile_test1.exists());
File myFile_test2 = new File(selectedfile_uri.getEncodedPath());
Log.e("TAG7", myFile_test2.getPath() + " .exists() "+myFile_test2.exists());
function_read_txt_file(myFile_test1); //returns FileNotFoundException
function_read_txt_file(myFile_test2); //returns FileNotFoundException
}
}
logcat:
E/TAG7: selectedfile_uri --- content://com.android.externalstorage.documents/document/primary%3Akote.txt
E/TAG7: /document/primary:kote.txt .exists() false
E/TAG7: /document/primary%3Akote.txt .exists() false
E/TAG7: FileNotFoundException
我在这里缺少什么?干杯
Uri
可能没有您文件的直接访问路径。您应该通过从 Uri
InputStream
来打开文件
Uri selectedfile_uri = intent.getData();
InputStream inputStream = getContentResolver().openInputStream()