我正在从服务器下载文件,出于某种原因,我无法确定下载的文件大小是否与原始文件大小不匹配。这是我的代码。获取与android下载代码不匹配的文件大小
private class dl extends AsyncTask<String,Integer,Void>
{
int size;
@Override
protected Void doInBackground(String... arg0) {
// TODO Auto-generated method stub
try{
URL myFileUrl = new URL("http://10.0.2.2:8080/testdlapps/chrome-beta.zip");
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setConnectTimeout(5000);
conn.connect();
InputStream is = conn.getInputStream();
size = conn.getContentLength();
Log.v("INFO---------------------", "size is " +size);
FileOutputStream fout1 = new FileOutputStream(Environment.getExternalStorageDirectory()+"/"+"xyz.zip");
BufferedOutputStream bos = new BufferedOutputStream(fout1);
byte[] b = new byte[1024]; int i=0, count=0;
while((count = is.read(b)) != -1)
{
bos.write(b,0,count);
i+=count;
publishProgress(i);
Log.v("INFO----------------------------",""+count);
}
fout1.close();
}catch(Exception e){
Log.v("INFO--------------------------","Error!!");
Log.v("INFO--------------------------",e.getMessage());
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
tv.setText("downloaded " + progress[0] + "/" + size); //tv is a TextView
}
}
当我运行应用程序,下载完成后,计数和大小是相同的,但实际的文件大小即/mnt/sdcard/xyz.zip总是小于大小。任何想法出了什么问题?
感谢您的代码,但它不会与Android操作系统比froyo更老的设备兼容(是的,当我发现它是要求的一部分时,我也感到震惊)。 AndroidHttpClient仅适用于2.2+ – 2012-02-24 06:55:49
关于onPostExecute的建议应该仍然有效 – sherpya 2012-02-24 16:23:03