5

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

Nikola
  • 87
  • 2
  • 7

1 Answers1

4

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()
Nabin Bhandari
  • 15,949
  • 6
  • 45
  • 59
  • now it is ok...thanks! actually I could do that with uri on KitKat - but now on Lollipop I have to use your solution – Nikola Oct 07 '17 at 11:36
  • Glad I could help :) – Nabin Bhandari Oct 07 '17 at 11:37
  • 1
    @Nikola: "I could do that with uri on KitKat" -- not really. It all depends on the `Uri` that you get back. Your code assumes that the `Uri` has a `file` scheme. It does not have to have that scheme on any version of Android. `openInputStream()` supports `file` and `content`, the two most likely `Uri` schemes. – CommonsWare Oct 07 '17 at 11:48
  • 1
    Your answer helped put my on the right track. Here are more details of what I did: https://stackoverflow.com/a/52231623 – Suragch Sep 08 '18 at 03:11