在android中选择文件后找不到文件错误

2023-12-20

我想在我的 Android 应用程序中打开 .pdf 文件。现在我可以浏览 pdf 文件,浏览文件后我得到文件未找到当我检查文件是否存在时出错。现在选择文件后我选择的文件 Uridata.getData()就好像

content://com.android.externalstorage.documents/document/6333-6131:SHIDHIN.pdf

以及我解析时使用的路径data.getData().getPath().toString()就好像

/document/6333-6131:SHIDHIN.pdf这是我的代码。请帮我。

// To Browse the file

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
startActivityForResult(intent, PICK_FILE_REQUEST);

选择文件后

//onActivityResult

public void onActivityResult(final int requestCode, int resultCode, Intent data) {
    try {
        switch (requestCode) {
            case PICK_FILE_REQUEST:
                if (resultCode == RESULT_OK) {
                    try {
                        Uri fileUri = data.getData();
                        String path  = fileUri.getPath().toString();
                        File f = new File(path);
                        if (f.exists()) {
                            System.out.println("\n**** Uri :> "+fileUri.toString());
                            System.out.println("\n**** Path :> "+path.toString());
                            final Intent intent = new Intent(MainActivity.this, ViewPdf.class);
                            intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
                            startActivity(intent);
                        } else {
                            System.out.println("\n**** File Not Exist :> "+path);
                        }

                    } catch (Exception e) {
                        ShowDialog_Ok("Error", "Cannot Open File");
                    }
                }
                break;
        }
    } catch (Exception e) {
    }
}

这不是答案,而是一种解决方法。

File file = new File("some_temp_path"); # you can also use app's internal cache to store the file
FileOutputStream fos = new FileOutputStream(file);

InputStream is = context.getContentResolver().openInputStream(uri);
byte[] buffer = new byte[1024];
int len = 0;
try {
    len = is.read(buffer);
    while (len != -1) {
        fos.write(buffer, 0, len);
        len = is.read(buffer);
    }

    fos.close();
} catch (IOException e) {
    e.printStackTrace();
}

将此文件的绝对路径传递给您的活动。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在android中选择文件后找不到文件错误 的相关文章

随机推荐