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

标签 java android pdf android-intent filenotfoundexception

我想在我的 Android 应用程序中打开一个 .pdf 文件。现在我可以浏览该 pdf 文件,浏览该文件后我收到未找到文件错误我检查文件是否存在。现在选择文件后,我选择的文件 Uri data.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();
}

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

关于java - 在android中选择文件后找不到文件错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30075095/

相关文章:

java - 自动将多个接口(interface)绑定(bind)到 Guice 中的一个实现

Android SQLiteDatabase.insert 与 SQLiteStatement.excuteinsert

javascript - 在 Javascript 中旋转对象标签 (PDF)

java - 定时器类中潜在的竞争条件?

java - 从适配器向 Activity 添加功能时遇到问题

java - 不同类型数据上的对象循环

java - 无法让 AutoCompleteTextView 与其他组件一起显示

android - 如何从 laravel web 应用程序创建 android 应用程序?

svn - 通过 apache webdav 访问 subversion 存储库时 Pdf 被破坏

c# - 将 PDF 流式传输到网页失败