android从assets文件夹访问pdf文件

时间:2015-01-12 05:07:37

标签: android file pdf android-intent android-assets

在我的应用程序中,我想在资源中存储PDF文件,当按下查看按钮时,应该通过设备中安装的第三方应用程序查看PDF。

通过使用以下代码,我尝试访问资产文件夹中的PDF文件,但应用程序说“文件不可用' 。我在stackoverflow上搜索了各种代码,但没有一个工作。但是当我试图提取APK文件时,我能够在资产文件夹中看到PDF文件。

以下是我尝试过的代码:

File file = new File("file://" + getFilesDir() + "/ccv.pdf");

            if (file.exists()) {

                Uri path = Uri.fromFile(file);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(path, "application/pdf");
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                try {
                    startActivity(intent);
                } 
                catch (ActivityNotFoundException e) {
                    Toast.makeText(home.this, 
                        "No Application Available to View PDF", 
                        Toast.LENGTH_SHORT).show();
                }
            }
            else
            {
                Toast.makeText(home.this, 
                        "File not available", 
                        Toast.LENGTH_SHORT).show();
            }

因此,请提供代码片段以访问资产文件夹中的PDF文件。

提前致谢

3 个答案:

答案 0 :(得分:1)

Try this

File file = new File("file:///android_asset" + "/ccv.pdf");

            if (file.exists()) {

                Uri path = Uri.fromFile(file);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(path, "application/pdf");
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                try {
                    startActivity(intent);
                } 
                catch (ActivityNotFoundException e) {
                    Toast.makeText(home.this, 
                        "No Application Available to View PDF", 
                        Toast.LENGTH_SHORT).show();
                }
            }
            else
            {
                Toast.makeText(home.this, 
                        "File not available", 
                        Toast.LENGTH_SHORT).show();
            }

答案 1 :(得分:0)

  

我试图访问资产文件夹

中的PDF文件

为此,

new File("file://" + getFilesDir() + "/ccv.pdf");  

不会让你获得资产路径。

getFilesDir()只是

  

返回文件系统所在目录的绝对路径   创建的文件

要访问资产,请使用getAssets()AssetManager

您可以参考how-to-access-file-under-assets-folder-in-android

答案 2 :(得分:0)

最后我找到了答案,无法使用File访问资产,只能使用Assetmanager访问它

AssetManager assetManager = getAssets();
InputStream ims = assetManager.open("ccv.pdf");
相关问题