1

I am trying to get the path of a file in order to read it.

Here's the code when I click on button I start OnBrowse() with the current view :

public void onBrowse(View view) {
        Intent chooseFile;
        Intent intent;
        chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
        chooseFile.addCategory(Intent.CATEGORY_OPENABLE);
        chooseFile.setType("*/*");
        intent = Intent.createChooser(chooseFile, "Choose a file");
        startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) return;
        String path     = "";
        if(requestCode == ACTIVITY_CHOOSE_FILE)
        {
            Uri uri = data.getData();
            Log.d("Path", ""+uri);
            File myFile = new File(uri.getPath());
            myFile.getAbsolutePath();
            loadFile(myFile.getAbsolutePath());
        }
    }

    public String getRealPathFromURI(Uri contentUri) {
        String [] proj      = {MediaStore.Images.Media.DATA};
        Cursor cursor       = getContentResolver().query( contentUri, proj, null, null,null);
        if (cursor == null) return null;
        int column_index    = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

Noe everything works, but myFile.getAbsolutePath() give me the following path :

/document/raw:/storage/emulated/0/Download/File.txt

When I think it it supposed to return just storage/emulated/0/Download/File.txt

So when I try to read the file it throw me an exception .

Thanks

Bobby
  • 4,372
  • 8
  • 47
  • 103

1 Answers1

1

If you just want to read the content of the uri it is much easier to use an Inputstream instead of a file. There is no need to translate to file. This also works with http, and ftp uri-s

InputStream in = getContentResolver().openInputStream(uri);
loadFromInputStream(in);

For details see sdk ContentResolver#openInputStream(uri)

k3b
  • 14,517
  • 7
  • 53
  • 85