简体   繁体   English

使用intent打开assets文件夹中的文件

[英]Opening a file present in assets folder using an intent

Hello I am tring to open a .pdf file present in a file using an intent but it is giving me 2 errors on the following line 您好我想使用intent打开文件中存在的.pdf文件,但它在以下行中给出了2个错误

File file = new File(getContext().getAssets().open("assets/test.pdf"));

Errors 错误
1.Unhandled java.IO.Exception. 1.未处理的java.IO.Exception。
2. getAssets() may produce java.lang.NullPointerException 2. getAssets()可能会产生java.lang.NullPointerException
Here us the code in a fragment 这里是片段中的代码

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    if (position == 0) {
        File file = new File(getContext().getAssets().open("assets/test.pdf"));
        if (file .exists())
        {
            Uri path = Uri.fromFile(file );
            Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
            pdfIntent.setDataAndType(path , "application/pdf");
            pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            try
            {
                startActivity(pdfIntent ); }
            catch (ActivityNotFoundException e)
            {
                Toast.makeText(getActivity(), "Please install a pdf file viewer",
                        Toast.LENGTH_LONG).show();
            }
        }
}
}
    File fileBrochure = new File(Environment.getExternalStorageDirectory() + "/" + "abc.pdf");
    if (!fileBrochure.exists())
    {
         CopyAssetsbrochure();
    } 

    /** PDF reader code */
    File file = new File(Environment.getExternalStorageDirectory() + "/" + "abc.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);
    try 
    {
        getApplicationContext().startActivity(intent);
    } 
    catch (ActivityNotFoundException e) 
    {
         Toast.makeText(SecondActivity.this, "NO Pdf Viewer", Toast.LENGTH_SHORT).show();
    }
}

//method to write the PDFs file to sd card
    private void CopyAssetsbrochure() {
        AssetManager assetManager = getAssets();
        String[] files = null;
        try 
        {
            files = assetManager.list("");
        } 
        catch (IOException e)
        {
            Log.e("tag", e.getMessage());
        }
        for(int i=0; i<files.length; i++)
        {
            String fStr = files[i];
            if(fStr.equalsIgnoreCase("abc.pdf"))
            {
                InputStream in = null;
                OutputStream out = null;
                try 
                {
                  in = assetManager.open(files[i]);
                  out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + files[i]);
                  copyFile(in, out);
                  in.close();
                  in = null;
                  out.flush();
                  out.close();
                  out = null;
                  break;
                } 
                catch(Exception e)
                {
                    Log.e("tag", e.getMessage());
                } 
            }
        }
    }

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

You cannot open the pdf file directly from the assets folder.You first have to write the file to sd card from assets folder and then read it from sd card 您无法直接从assets文件夹打开pdf文件。您首先必须将文件从assets文件夹写入SD卡,然后从SD卡读取它

try with the file provider 尝试使用文件提供程序

 Intent intent = new Intent(Intent.ACTION_VIEW);

    // set flag to give temporary permission to external app to use your FileProvider
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    // generate URI, I defined authority as the application ID in the Manifest, the last param is file I want to open
    String uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID, file);

    // I am opening a PDF file so I give it a valid MIME type
    intent.setDataAndType(uri, "application/pdf");

    // validate that the device can open your File!
    PackageManager pm = getActivity().getPackageManager();
    if (intent.resolveActivity(pm) != null) {
        startActivity(intent);
    }

To serve a file from assets to another app you need to use a provider. 要将文件从资源提供给另一个应用程序,您需要使用提供程序。

Google for the StreamProvider of CommonsWare. 谷歌为CommonsWare的StreamProvider。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM