简体   繁体   中英

Android correct way to get File from Uri

I pick a PDF from local archive using:

startActivityForResult(Intent.createChooser(new Intent().setType("application/pdf").setAction(Intent.ACTION_GET_CONTENT), getString(R.string.str_select_file)), request_id_archive);

and manage result:

    @Override
    protected void onActivityResult(int request_code, int result_code, Intent data) {
        super.onActivityResult(request_code, result_code, data);

        if (request_code == request_id_archive && result_code == RESULT_OK && data != null && data.getData() != null) {
            Uri myuri = data.getData();
            String mypath = myuri.getPath();
            File myfile = new File(mypath);
            Log.d("mylog1", uri.toString());
            Log.d("mylog2", uri.getPath());
            Log.d("mylog3", f.getPath());
            Log.d("mylog4", f.toString());
            Log.d("mylog5", Boolean.toString(f.exists()));
        }
        else {...}

It seems that the file is not succesfully created. Result of my Logs are:

  • mylog1 -> content://media/external/file/7406
  • mylog2 -> /external/file/7406
  • mylog3 -> /external/file/7406
  • mylog4 -> /external/file/7406
  • mylog5 -> false

Method file.exist() return me that the file do not exist. Why?

In other code I try to manage the file for many other operations:

...
InputStream inputStream = new FileInputStream(file);
...

But my app crash ang in Logcat I see:

java.io.FileNotFoundException: /document/raw:/storage/emulated/0/Download/20180702_121938.pdf (No such file or directory)

I'm testing my code on Android 7.

You need to replace 'document/raw' with an empty string , so you need to add this code before accessing the file:

if(mypath.contains("document/raw:")){
    mypath = mypath.replace("/document/raw:","");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM