读取并打开assets下面的pdf文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35821446/article/details/74748456

 总体流程:

Android不能直接打开pdf文件,无论是服务器端的还是本地的,都不可直接打开,在此主要介绍,打开放在assets下的pdf文件:

Android不可直接打开assets下的pdf文件,这就需要先从assets读取到内存中,然后保存到本地,再打开本地的pdf文件即可,话不多说看代码:



 //从assets 文件夹中获取文件并读取数据   

public File getFromAssets(String fileName,File file){   
       String result = "";   
       InputStream in=null;
       OutputStream out = null;
           try {   
               in = getResources().getAssets().open(fileName);   
               out=new FileOutputStream(file);
               //获取文件的字节数   
               int lenght = in.available();   
               //创建byte数组   
               byte[]  buffer = new byte[lenght];   
               //将文件中的数据读到byte数组中   
              int bytes= in.read(buffer);   
               //.getString(buffer, ENCODING);
               //将读取的数据写到本地
out.write(buffer, 0, bytes);
               in.close();
               out.close();
           } catch (Exception e) {   
               e.printStackTrace();  
               file.delete();
           }finally{
   
   
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
}
}
   
           return file;   
   }  
});




// 打开PDF文件


private String reportUrl = "file:///android_asset/happywinner.pdf";
private String urlName = "happywinner.pdf";


((TextView) findViewById(R.id.freego_reader_pdf))
.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String path = Environment
.getExternalStorageDirectory()
+ "/Download/";
String[] splitStrings = reportUrl.split("/");
String[] nameStrings = splitStrings[splitStrings.length - 1]
.split(".pdf");


String fileName = nameStrings[0] + ".pdf";
File file = new File(path + fileName);

Uri path1 = Uri.fromFile(getFromAssets(urlName,file));
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setDataAndType(path1, "applicationf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);


try {
LifeHappyWinnerOnlineInsuranceActivity.this
.startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(
LifeHappyWinnerOnlineInsuranceActivity.this,
"打开失败", 1);
}


}


猜你喜欢

转载自blog.csdn.net/qq_35821446/article/details/74748456