如何从assets文件夹中打开Android中的PDF文件?

前端之家收集整理的这篇文章主要介绍了如何从assets文件夹中打开Android中的PDF文件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有人知道如何在 Android中打开PDF文件?我的代码看起来像这样:
  1. public class SampleActivity extends Activity {
  2.  
  3. @Override
  4. protected void onCreate(Bundle savedInstanceState) {
  5. super.onCreate(savedInstanceState);
  6. setContentView(R.layout.main);
  7. CopyReadAssets();
  8. }
  9.  
  10. private void CopyReadAssets() {
  11. AssetManager assetManager = getAssets();
  12.  
  13. InputStream in = null;
  14. OutputStream out = null;
  15. File file = new File(getFilesDir(),"git.pdf");
  16. try {
  17. in = assetManager.open("git.pdf");
  18. out = openFileOutput(file.getName(),Context.MODE_WORLD_READABLE);
  19.  
  20. copyFile(in,out);
  21. in.close();
  22. in = null;
  23. out.flush();
  24. out.close();
  25. out = null;
  26. } catch (Exception e) {
  27. Log.e("tag",e.getMessage());
  28. }
  29.  
  30. Intent intent = new Intent(Intent.ACTION_VIEW);
  31. intent.setDataAndType(
  32. Uri.parse("file://" + getFilesDir() + "/git.pdf"),"application/pdf");
  33.  
  34. startActivity(intent);
  35. }
  36.  
  37. private void copyFile(InputStream in,OutputStream out) throws IOException {
  38. byte[] buffer = new byte[1024];
  39. int read;
  40. while ((read = in.read(buffer)) != -1) {
  41. out.write(buffer,read);
  42. }
  43. }
  44. }

解决方法

以下是从资产文件夹打开pdf文件代码,但您必须在设备上安装pdf阅读器:
  1. private void CopyAssets() {
  2.  
  3. AssetManager assetManager = getAssets();
  4.  
  5. InputStream in = null;
  6. OutputStream out = null;
  7. File file = new File(getFilesDir(),"fileName.pdf");
  8. try {
  9. in = assetManager.open("fileName.pdf");
  10. out = openFileOutput(file.getName(),e.getMessage());
  11. }
  12.  
  13. Intent intent = new Intent(Intent.ACTION_VIEW);
  14. intent.setDataAndType(
  15. Uri.parse("file://" + getFilesDir() + "/fileName.pdf"),read);
  16. }
  17. }

猜你在找的Android相关文章