Android - 从资产\ PDF显示访问文件

Evi*_*arS 9 java android assets android-intent

我试图检索存储在assets目录中的文件的引用到名为的文件myfile.pdf.我试过这样做:

File file = new File("android_assest/myfile.pdf);
Log.d("myTag", "" + file.isFile());
Run Code Online (Sandbox Code Playgroud)

不知何故,false当目录中myfile.pdf存在do 时,我得到了assets.我验证使用它getAssets().list("")Log.d()返回的数组中的每个元素.

更多其中,我试图获取PDF文件的参考,然后使用已安装在设备上的任何PDF查看器,以便查看PDF.

我想自从上一个问题(检索对文件的引用)返回false后,下一个剪切代码失败:

Intent i = new Intent(Intent.ACTION_VIEW,
    Uri.parse("file:///android_asset/myfile.pdf"));
startActivity(i);
Run Code Online (Sandbox Code Playgroud)

任何人都有一个线索,为什么我无法检索文件的引用?为什么我不能使用已安装的PDF查看器来显示PDF(在检索PDF文件的引用后)?

谢谢.

Vip*_*hah 24

正如Barak所说,您可以将其从资产中复制到内部存储或SD卡,并使用内置的pdf应用程序从那里打开它.

以下代码片段将帮助您.(我已更新此代码以写入和读取内部存储中的文件.

但我不推荐这种方法,因为pdf文件的大小可能超过100mb.

因此不建议将该大文件保存到内部存储中

同时确保将文件保存到您使用的内部存储器中

openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
Run Code Online (Sandbox Code Playgroud)

然后只有其他应用程序可以读取它.

检查以下代码段.

package org.sample;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

public class SampleActivity extends Activity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        CopyReadAssets();

    }

    private void CopyReadAssets()
    {
        AssetManager assetManager = getAssets();

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

            copyFile(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() + "/git.pdf"),
                "application/pdf");

        startActivity(intent);
    }

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

}
Run Code Online (Sandbox Code Playgroud)

一定要包括

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

在清单中