Android从资产文件夹中读取pdf文件

问题描述:

我尝试在资产文件夹中读取pdf文件存储。我看到这个解决方案: Read a pdf file from assets folderAndroid从资产文件夹中读取pdf文件

但像评论说这不工作了,该文件无法找到,是否有另一种解决方案直接读取PDF文件,没有复制PDF在外部存储? 我不希望我的PdfRenderer最小API使用的是17

或许这可以成为有用的人,所以我张贴我的答案:

private void openPdf(String pdfName){ 
    AssetManager assetManager = getAssets(); 

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

     byte[] buffer = new byte[1024]; 
     int read; 
     while ((read = in.read(buffer)) != -1) 
     { 
      out.write(buffer, 0, read); 
     } 
     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() + "/"+pdfName), 
      "application/pdf"); 

    startActivity(intent); 
} 

PDF文件是资产的文件夹内的商店