作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在编写一个应用程序,当您单击一个按钮时它会打开一个 pdf 文件。下面是我的代码:
File pdfFile = new File(
"android.resource://com.dave.pdfviewer/"
+ R.raw.userguide);
Uri path = Uri.fromFile(pdfFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(path, "application/pdf");
startActivity(intent);
但是,当我运行它并按下按钮时,它显示“无法打开文档,因为它不是有效的 PDF 文档”。这让我发疯。我是否正确访问文件?有任何想法吗?谢谢
最佳答案
您必须将 pdf 从 assets 文件夹复制到 sdcard 文件夹。
.....
copyFile(this.getAssets().open("userguide.pdf"), new FileOutputStream(new File(getFilesDir(), "yourPath/userguide.pdf")));
File pdfFile = new File(getFilesDir(), "yourPath/userguide.pdf"); Uri path = Uri.fromFile(pdfFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(path, "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);
}
}
关于android - 如何从 res/raw 文件夹打开 PDF 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13517412/
我是一名优秀的程序员,十分优秀!