2013-02-21 41 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

相關問題