Android从资源文件夹中读取PDF文件

时间:2014-01-03 06:39:57

标签: android android-layout pdf android-intent android-listview

我有需要放在asstes文件夹中的PDF文件列表,我的要求是从asstes中读取文件并将其显示在listview中。 如果我们点击每个列表项需要阅读相应的PDF文件

我已关注此博客http://androidcodeexamples.blogspot.in/2013/03/how-to-read-pdf-files-in-android.html

但是他们已经从外部存储目录中读取了PDF文件

我想从Asstes Folder

实现相同的阅读文件

任何人都可以帮助如何实现从asstes中读取文件的相同示例?

1 个答案:

答案 0 :(得分:2)

您无法直接从资源文件夹中打开pdf文件。您首先必须将文件从资源文件夹写入SD卡,然后从SD卡中读取。

尝试以下代码来复制和读取资产文件夹中的文件:

 //method to write the PDFs file to sd card 
 private void PDFFileCopyandReadAssets()
    {
        AssetManager assetManager = getAssets();

        InputStream in = null;
        OutputStream out = null;
        File file = new File(getFilesDir(), "test.pdf");
        try
        {
            in = assetManager.open("test.pdf");
            out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);

            readFile(in, out);
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
        } catch (Exception e)
        {
            Log.e("tag", e.getMessage());
        }

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(
                Uri.parse("file://" + getFilesDir() + "/test.pdf"),
                "application/pdf");

        startActivity(intent);
    }

    private void readFile(InputStream in, OutputStream out) throws IOException
    {
        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1)
        {
            out.write(buffer, 0, read);
        }
    }

从SD卡打开文件,如下所示:

File file = new File("/sdcard/test.pdf");        
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

还提供在清单中写入外部存储空间的权限。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />