Android get the real path and file name from Uri

2019-09-13 23:22发布

public void fileSearching(){
    try{
        // find1, find2 are buttons that open the file explorer
        find1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                Intent i = new Intent();
                i.setAction(Intent.ACTION_GET_CONTENT);
                i.setType("file/*");
                check = 0;
                startActivityForResult(i, CODE);
            }
        });
        find2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent();
                i.setAction(Intent.ACTION_GET_CONTENT);
                i.setType("file/*");
                check = 1;
                startActivityForResult(i, CODE);
            }
        });
    }
    catch (Exception ex){}
}
@Override
public void onActivityResult(int request, int result, Intent data){
    if (request == CODE && result == RESULT_OK){
        Uri u = data.getData();
        String path = data.getData().getPath();
    }
}

Retrurns /external/file/59 but i need /sdcard/downloads/... + file name
I need this because i want to get a sha-1,md5,... hash for any file.
If i use the "/external/file/xx" it gives me a FileNotFoundException.
I've tried some solutions that were already presented but none seemed to work for me or i didn't know how to use it

标签: android hash
1条回答
地球回转人心会变
2楼-- · 2019-09-13 23:49

Retrurns /external/file/59

That is because you did not look at the scheme of the Uri. getPath() only has meaning if the scheme is file. You will rarely get a Uri with a file scheme. Usually, it will have a content scheme, in which case the path is meaningless to you.

I need this because i want to get a sha-1,md5,... hash for any file.

Use ContentResolver and openInputStream() to get an InputStream on the content identified by the Uri. Pass that InputStream to your hashing algorithm.

查看更多
登录 后发表回答