by click on some button - an intent for selecting txt file is created:
Intent intent = new Intent()
.setType("text/plain")
.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select a TXT file"), 123);
And it works OK - I select txt file from root folder on phone internal memory --- /storage/emulated/0/kote.txt
But when I try to read data from it, I get 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
What I'm missing here? cheers
Uri
may not have the directly accessible path to your file. You should open the file by opening the InputStream
from the Uri
Uri selectedfile_uri = intent.getData();
InputStream inputStream = getContentResolver().openInputStream()