【问题标题】:Android Reading PDF files from asstes folderAndroid 从 assets 文件夹中读取 PDF 文件
【发布时间】:2014-01-03 06:39:57
【问题描述】:

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

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

但是这里他们给出了从外部存储目录读取 PDF 文件

我想从 Asstes 文件夹中实现相同的读取文件

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

【问题讨论】:

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


【解决方案1】:

您不能直接从assets文件夹打开pdf文件。您必须先将文件从assets文件夹写入sd卡,然后从sd卡读取。

试试下面的代码从 assets 文件夹中复制和读取文件:

 //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);
        }
    }

从sdcard打开文件如下:

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" />

【讨论】:

  • @GrlsHu 问题是关于pdf文件的
  • @GrlsHu 从 Assets 创建文件的 SD 卡中的目录名称是什么?
  • 您可以指定自己的sd卡目录名,用于创建和存储pdf文件。
  • 请提供一些示例代码行(在SD卡中创建目录)
  • 最后一个问题我正在实现一个图书应用程序(PDF 文件阅读)有没有办法从我们的应用程序中读取文件?
猜你喜欢
  • 2013-06-09
  • 1970-01-01
  • 2015-03-09
  • 1970-01-01
  • 2011-11-21
  • 2018-01-19
  • 2021-08-28
  • 2014-06-22
  • 2023-03-24
相关资源
最近更新 更多