单击某个按钮 - 创建选择txt文件的意图:
Intent intent = new Intent()
.setType("text/plain")
.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select a TXT file"), 123);
它工作正常 - 我从手机内存上的根文件夹中选择了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
我在这里失踪了什么?欢呼声
答案 0 :(得分:3)
Uri
可能没有您文件的直接可访问路径。您应该打开InputStream
Uri
来打开文件
Uri selectedfile_uri = intent.getData();
InputStream inputStream = getContentResolver().openInputStream()