2012-07-31 43 views

回答

4
public void downloadFromUrl(String url, String outputFileName) { 


    File dir = new File(Environment.getExternalStorageDirectory() + "/"); 
    if (dir.exists() == false) { 
     dir.mkdirs(); 
    } 
    try { 
     URL downloadUrl = new URL(url); // you can write any link here 

     File file = new File(dir, outputFileName);   
     /* Open a connection to that URL. */ 
     URLConnection ucon = downloadUrl.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(); 




    } catch (IOException e) { 
     e.printStackTrace(); 


    } 



} 
+0

謝謝.. 它的工作原理 – TheReaper 2012-08-01 11:35:00

+0

作爲一個魅力... 有時它可能會拋出「networkOnMainThreadException」。在這種情況下,在AsnycTask中執行此過程並且沒問題。 – 2016-03-31 12:45:34

+0

工程就像一個魅力。非常感謝你 :) – 2017-08-03 07:40:34

0

使用DownloadManager下載Url,雖然我不確定是否有任何重定向,但DownloadManager會照顧它。

+0

哇,我不明白你與你的連接和管理人員真棒例子,你inputstreams ...我閱讀文檔....但我不知道我怎樣才能把「公共靜態最後絃樂COLUMN_REASON」嗯...(諷刺) – delive 2015-11-20 16:48:10