2013-02-21 40 views
0

使用此代码我可以从Android下载URL并将其保存到SDCard中,有什么方法可以以编程方式打开此文件吗?如何以编程方式在Android中打开下载的文件?

Can Intent help in this?

private static class Task extends AsyncTask<Void, Void, Void> { 

    static String DownloadUrl = "http://00.00.00.00/abc.crt"; 
    static String fileName = "def.crt"; 

异步任务下载

@Override 
protected Void doInBackground(Void... arg0) { 
    DownloadFromUrl(); 
    return null; 
} 


public static void DownloadFromUrl() { 

    try { 
      File root = android.os.Environment.getExternalStorageDirectory();    

      File dir = new File (root.getAbsolutePath() + "/SDCard"); 
      if(dir.exists()==false) { 
       dir.mkdirs(); 
      } 

      URL url = new URL(DownloadUrl); //you can write here any link 
      File file = new File(dir, fileName); 

      long startTime = System.currentTimeMillis(); 
      Log.d("DownloadManager", "download begining"); 
      Log.d("DownloadManager", "download url:" + url); 
      Log.d("DownloadManager", "downloaded file name:" + fileName); 

      /* Open a connection to that URL. */ 
      URLConnection ucon = url.openConnection(); 

      /* 
      * Define InputStreams to read from the URLConnection. 
      */ 
      InputStream is = ucon.getInputStream(); 
      BufferedInputStream bis = new BufferedInputStream(is); 

      /* 
      * Read bytes to the Buffer until there is nothing more to read(-1). 
      */ 
      ByteArrayBuffer baf = new ByteArrayBuffer(5000); 
      int current = 0; 
      while ((current = bis.read()) != -1) { 
       baf.append((byte) current); 
      } 

      /* Convert the Bytes read to a String. */ 
      FileOutputStream fos = new FileOutputStream(file); 
      fos.write(baf.toByteArray()); 
      fos.flush(); 
      fos.close(); 
      Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime)/1000) + " sec"); 




    } catch (IOException e) { 
     Log.d("DownloadManager", "Error: " + e); 
    } 

} 


} 
+0

你想如何打开它?作为文本或二进制或与应用程序? – Gjordis 2013-02-21 09:04:50

+0

是的,'intent'是要走的路。看到Google或[this](http://stackoverflow.com/questions/7009452/how-to-launch-browser-to-open-local-file)。 – adrianp 2013-02-21 09:04:52

+0

当你说'开放'时,你是什么意思?什么是文件类型(如.crt)?数据是什么?串?音频? – 2013-02-21 09:05:06

回答

0

使用一个FileInputStream和如果该文件是一个特定扩展名的有可能是加载它的其他方式下载的文件加载到内存 http://developer.android.com/reference/java/io/FileInputStream.html

不涉及将其解析为字节数组

+0

感谢Udrian&Matt,理想的.CRT是VPN证书文件,当安装弹出通知输入证书名称,然后安装文件的Android VPN应用程序。我猜如果我们要读取一个文件,那么我们需要FileInputStream,打开这个文件不应该被意图使用? – user1223035 2013-02-21 09:12:15

+0

GJordis它将打开为二进制文件,打开时会调用VPN应用程序 – user1223035 2013-02-21 09:15:04

+0

我不知何故错过了它是一个.CRT文件。是的,如果你的意图是提示用户在你的应用程序之外打开这个文件,那么你应该使用一个意图。这可能会帮助你一点http://indyvision.net/2010/03/android-using-intents-open-files/ – Udrian 2013-02-21 09:16:15

相关问题