来自Uri的Android getPath()无法正常工作

时间:2017-11-08 06:27:15

标签: android file path

on huawei honor 8 with android 7.0 uri.getPath()返回类似于/ external / file / 3344的内容,而不是文件的真实路径。这个代码在许多设备上也可以正常工作,也适用于android 7.0的android模拟器uri.getPath()返回/storage/emulated/0/PCalculator/main.js但不返回荣誉8.我使用Intent在我的程序中选择一个文件,如下所示:

private void fileBrowse(){
    Intent intent = new Intent();
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("*/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser
                (intent,"Open File"),RCODE_OPENFILE);
}

在onActivityResult中我想读取如下文件:

public void onActivityResult(int requestCode,int resultCode,Intent data) {
    super.onActivityResult(requestCode,resultCode,data);

    switch(requestCode){
        case RCODE_OPENFILE:
            if(resultCode == RESULT_OK &&
                    data != null && data.getData() != null){
                fileOpen(data.getData());
            }
            break;
    }

}

fileOpen函数:

private void fileOpen(Uri uri){

    File mFile = new File(uri.getPath());
    StringBuilder mText = new StringBuilder();

    try {
        BufferedReader br = new BufferedReader(new FileReader(mFile));
        String line;

        while ((line = br.readLine()) != null) {
            mText.append(line);
            mText.append('\n');
        }
        br.close();
    }
    catch (IOException e) {
        e.printStackTrace();
    }

    etCode.setText(mText);
    tvTitle.setText(mFile.getName());
}

0 个答案:

没有答案