在我的应用程序,我有要求从URL下载MP3文件。我正在使用异步任务下载文件。出于测试目的,我已将文件保存在保管箱中。问题是,它不是下载完整的文件。实际文件大小为5 MB。但是,它只下载29 KB的数据。当我检查内容的长度时,它显示-1。我不明白问题在哪里。下面,我张贴我的代码。Android:完整的文件没有从网址下载
@Override
protected Void doInBackground(String... sUrl)
{
InputStream input = null;
OutputStream output = null;
try
{
URL link = new URL(sUrl[0]);
HttpURLConnection urlConnection = (HttpURLConnection)link.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
int fileLength = urlConnection.getContentLength();
Log.v("Download file length", ""+fileLength);
input = urlConnection.getInputStream();
int downloadedSize = 0;
output = new FileOutputStream(Environment.getExternalStorageDirectory()
.getAbsolutePath()+"/audiofolder/1.mp3.mp3");
byte[] data = new byte[1024];
int bufferLength = 0;
while (((bufferLength = input.read(data)) > 0))
{
output.write(data, 0, bufferLength);
downloadedSize += bufferLength;
publishProgress((int)((downloadedSize/fileLength) * 100));
}//while
output.flush();
output.close();
input.close();
}//try
catch (MalformedURLException e)
{
e.printStackTrace();
}//catch
catch (IOException e)
{
e.printStackTrace();
}//catch
return null;
}//diInBackground
2012-10-03
Nitish