我正在從服務器下載文件,出於某種原因,我無法確定下載的文件大小是否與原始文件大小不匹配。這是我的代碼。獲取與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