File file = new File("android.resource://com.baltech.PdfReader/assets/raw/"+filename);
if (file.exists()) {
Uri targetUri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(targetUri, "application/pdf");
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText(PdfReaderActivity.this, "No Application Available to View PDF", Toast.LENGTH_SHORT).show();
}
我想阅读资产文件夹中的.pdf文件。我在文件名中给出了什么路径。请帮助。谢谢
答案 0 :(得分:3)
我不确定你是否已经得到了答案,看起来很旧,但这对我有用。
//you need to copy the input stream to a new file, so store it elsewhere
//this stores it to the sdcard in a new folder "MyApp"
String filename = Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyApp/solicitation_form.pdf";
AssetManager assetManager = getAssets();
try {
InputStream pdfFileStream = assetManager.open("solicitation_form.pdf");
CreateFileFromInputStream(pdfFileStream, filename);
} catch (IOException e1) {
e1.printStackTrace();
}
File pdfFile = new File(filename);
CreateFileFromInputStream函数如下
public void CreateFileFromInputStream(InputStream inStream, String path) throws IOException {
// write the inputStream to a FileOutputStream
OutputStream out = new FileOutputStream(new File(path));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
inStream.close();
out.flush();
out.close();
}
真的希望这可以帮助其他读这篇文章的人。
答案 1 :(得分:2)
File file = new File("file:///android_asset/raw/"+filename);
用以下代替上面的行并尝试..
File file = new File("android.resource://com.com.com/raw/"+filename);
并放置PDF文件原始文件夹而不是资产。同时使用您的包名更改com.com.com。
答案 2 :(得分:1)
由于资产文件存储在apk文件中,因此资产文件夹没有绝对路径。 您可以使用解决方法创建用作缓冲区的新文件。
您应该使用AssetManager:
AssetManager mngr = getAssets();
InputStream ip = mngr.open(<filename in the assets folder>);
File assetFile = createFileFromInputStream(ip);
private File createFileFromInputStream(InputStream ip);
try{
File f=new File(<filename>);
OutputStream out=new FileOutputStream(f);
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0)
out.write(buf,0,len);
out.close();
inputStream.close();
}catch (IOException e){}
}
}