Android:从URL下载

时间:2014-04-18 07:16:27

标签: java android

我正在网上尝试一个示例下载代码,我发现它下载到大约13KB然后退出。该文件是4 MB。任何人都可以帮我解释一下这是为什么吗?这是代码。感谢。

//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-1getContentLength() ...可能是因为标题中缺少内容长度。

1 个答案:

答案 0 :(得分: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线程上。我相信你会得到你需要的东西