2014-04-18 94 views
0

我正在嘗試在線下載代碼示例,我發現它下載到大約13KB然後退出。該文件是4 MB。任何人都可以幫我解釋這是爲什麼嗎?這是代碼。謝謝。Android:從URL下載

//this is the total size of the file 
int totalSize = urlConnection.getContentLength(); 
//variable to store total downloaded bytes 
int downloadedSize = 0; 

//create a buffer... 
byte[] buffer = new byte[1024]; 
int bufferLength = 0; //used to store a temporary size of the buffer 

//now, read through the input buffer and write the contents to the file 
while ((bufferLength = inputStream.read(buffer)) > 0) { 
    //add the data in the buffer to the file in the file output stream (the file on the sd card 
    fileOutput.write(buffer, 0, bufferLength); 
    //add up the size so we know how much is downloaded 
    downloadedSize += bufferLength; 
    //this is where you would do something to report the prgress, like this maybe 
    //updateProgress(downloadedSize, totalSize); 
    Log.w("DOWNLOAD" , "progress " + downloadedSize + "/" + totalSize); 

我注意到totalSize-1調用getContentLength()時......可能是因爲從頭部遺漏的內容長度。

+0

你在哪裏寫數據? SD卡? :) – Pphoenix

+1

當內容長度是'-1'時,它的**空**。 – Astrobleme

+0

你在** Manifest **中聲明瞭「INTERNET」權限嗎?和'WRITE_EXTERNAL_STORAGE'權限在存儲中寫入文件? –

回答

0

首先在您的清單文件中添加這兩種權限<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />然後按照此鏈接(http://velmuruganandroidcoding.blogspot.in/2013/07/download-image-from-url-to-sd-card-in.html),
並確保HTTP調用絕不能在UI線程。我相信你會得到你需要的東西

+0

感謝您的回覆。但是,您提供的示例不起作用。但是,它可以與其他網址一起使用。它似乎與contentLength不是由服務器提供的。有沒有辦法下載這個文件?謝謝。 – user1291899