【问题标题】:Android open PDF : File not foundAndroid打开PDF:找不到文件
【发布时间】:2014-08-20 08:39:18
【问题描述】:

我尝试在我的应用程序中打开 PDF。 首先,我这样创建 PDF:

String filename = Environment.getExternalStorageDirectory().toString()+"/mypdf.pdf";
File file = new File(filename);

try {
    FileOutputStream bos = new FileOutputStream(file);
    bos.write(Base64.decode(base64, 0));
    bos.flush();
    bos.close();
} catch (IOException e) {
    Log.e(TAG, "IOError with PDF");
    e.printStackTrace();
}

Intent intent = new Intent(this, PdfActivity.class);
intent.putExtra("file", filename);
startActivity(intent);

该文件创建良好且可读,我可以使用 ESExplorer 应用程序打开它。 该文件位于/storage/emulated/0/myfile.pdf

在 PdfActivity 中我尝试打开 PDF:

Bundle extras = getIntent().getExtras();
String url = extras.getString("file");

File file = new File(url);
try {
    if (file.exists()) {
        Uri path = Uri.parse(url);
        Intent objIntent = new Intent(Intent.ACTION_VIEW);
        objIntent.setDataAndType(path, "application/pdf");
        objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(objIntent);
    } else {
        Toast.makeText(this, "File NotFound", Toast.LENGTH_SHORT).show();
    }
} catch (ActivityNotFoundException e) {
    Toast.makeText(this, "No Viewer Application Found", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
    e.printStackTrace();
}

file.exists() return true,Intent 开始,但我的 PDF 阅读器说:“找不到文件” 我已经添加了对外部存储的读写权限。

有人知道为什么它无法访问我的文件吗?

【问题讨论】:

    标签: android file pdf


    【解决方案1】:
     objIntent.setDataAndType(url, "application/pdf");
    

    在你的第二个片段中使用上面的行也将 String url 声明为 全局变量 希望它会帮助你如果它不起作用尝试使用文件路径的硬编码值看看它是否有效?

    你确定文件存在吗?也检查一下这种情况:)

    【讨论】:

    • 此解决方案不起作用,因为第一个参数必须是 URI。我尝试使用以下命令加载 PDF: Uri uri = Uri.parse("/storage/emulated/0/myfile.pdf");把我得到相同的结果。
    • 文件存在,如果我删除它,它会重新创建,我可以用 Adob​​e 应用程序打开 PDF。
    【解决方案2】:

    我找到了解决方案。 我已经像这样替换了 Uri:

    Uri path = Uri.fromFile(file);
    

    而且它有效!

    【讨论】:

      猜你喜欢
      • 2021-03-27
      • 2013-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2019-10-10
      • 1970-01-01
      相关资源
      最近更新 更多