Android未知格式文件下载及展示

1,456 阅读2分钟
  • 最近项目需要通过指定地址+id的方式下载文件并且展示,文件格式未知,可能是txt、xls、pdf、doc,那么问题来了,怎么在未知格式的情况下下载文件并展示呢? 通过参考PC端做法,完美的解决了这个问题,附上完整代码: private void loadPdf(String id) { String urlString = "http://********/irp/reportDownload?id=" + id; try { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); //实现连接 connection.connect();

              String temp = connection.getHeaderField("Content-Disposition");
    
              Log.w(TAG, "HeaderField=" + temp);
              if (connection.getResponseCode() == 200) {
                  InputStream is = connection.getInputStream();
                  //以下为下载操作
                  byte[] arr = new byte[1];
                  ByteArrayOutputStream baos = new ByteArrayOutputStream();
                  BufferedOutputStream bos = new BufferedOutputStream(baos);
                  int n = is.read(arr);
                  while (n > 0) {
                      bos.write(arr);
                      n = is.read(arr);
                  }
                  bos.close();
                  Log.w(TAG, "result=" + baos.toString());
                  String path = Environment.getExternalStorageDirectory()
                      + "/download/";
                  Log.w(TAG, "文件格式=" + temp.substring(temp.lastIndexOf("."), temp.length()));
                  String filename = id + temp.substring(temp.lastIndexOf("."), temp.length());
                  Log.w(TAG, "文件名称=" + filename);
                  path = path + filename;
                  File file = new File(path);
                  FileOutputStream fos = new FileOutputStream(file);
                  fos.write(baos.toByteArray());
                  fos.close();
                  //关闭网络连接
                  connection.disconnect();
                  Log.w(TAG, "下载完成");
                  if (file.exists()) {
                      Uri path1 = Uri.fromFile(file);
                      Intent intent = new Intent(Intent.ACTION_VIEW);
                      intent.setDataAndType(path1, getMIMEType(file));
                      intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    
                      try {
                          startActivity(intent);
                      } catch (ActivityNotFoundException e) {
                          Log.w(TAG, "打开失败");
                      }
                  }
              } else {
                  mHandler.sendEmptyMessage(0xBBB);
                  //文件不存在
             }
          } catch (IOException e) {
              Log.w(TAG, "下载异常=" + e.getMessage());
         }
    

这样通过connection.getHeaderField("Content-Disposition");可以获取到带格式的文件名称。 接下来获取到了文件名称,但是如何打开呢? private final String[][] MAP_MIME = { //{后缀名, MIME类型} {".doc", "application/msword"}, {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}, {".xls", "application/vnd.ms-excel"}, {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}, {".htm", "text/html"}, {".html", "text/html"}, {".java", "text/plain"}, {".jpeg", "image/jpeg"}, {".jpg", "image/jpeg"}, {".js", "application/x-javascript"}, {".log", "text/plain"}, {".pdf", "application/pdf"}, {".png", "image/png"}, {".pps", "application/vnd.ms-powerpoint"}, {".ppt", "application/vnd.ms-powerpoint"}, {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"}, {".txt", "text/plain"}, {".wps", "application/vnd.ms-works"}, {".xml", "text/plain"}, {"", "/"} }; /** * 根据文件后缀名获得对应的MIME类型。 * * @param file */ private String getMIMEType(File file) {

        String type = "*/*";
        String fName = file.getName();
        //获取后缀名前的分隔符"."在fName中的位置。
        int dotIndex = fName.lastIndexOf(".");
        if (dotIndex < 0) {
            return type;
        }
        /* 获取文件的后缀名 */
        String end = fName.substring(dotIndex, fName.length()).toLowerCase();
        if ("".equals(end)) return type;
        //在MIME和文件类型的匹配表中找到对应的MIME类型。
        for (int i = 0; i < MAP_MIME.length; i++) { //MAP_MIME??在这里你一定有疑问,这个MIME_MapTable是什么?
        if (end.equals(MAP_MIME[i][0]))
            type = MAP_MIME[i][1];
        }
        return type;
    }

这样不管下载的文件只要包含在MAP_MIME 数组里的就都可以打开