获取与android下载代码不匹配的文件大小
我正在从服务器下载一个文件,由于某种原因我无法确定,下载的文件大小与原始文件大小不匹配。这是我的密码获取与android下载代码不匹配的文件大小,android,Android,我正在从服务器下载一个文件,由于某种原因我无法确定,下载的文件大小与原始文件大小不匹配。这是我的密码 private class dl extends AsyncTask<String,Integer,Void> { int size; @Override protected Void doInBackground(String... arg0) { // TODO Auto-generated method stub try{
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
}
}
私有类dl扩展异步任务
{
整数大小;
@凌驾
受保护的Void doInBackground(字符串…arg0){
//TODO自动生成的方法存根
试一试{
URL myFileUrl=新URL(“http://10.0.2.2:8080/testdlapps/chrome-beta.zip),;
HttpURLConnection conn=(HttpURLConnection)myFileUrl.openConnection();
连接设置输出(真);
conn.setRequestMethod(“GET”);
conn.setDoInput(真);
连接设置连接超时(5000);
连接();
InputStream is=conn.getInputStream();
size=conn.getContentLength();
Log.v(“信息-----------------”,“大小为”+大小);
FileOutputStream fout1=新的FileOutputStream(Environment.getExternalStorageDirectory()+“/”+“xyz.zip”);
BufferedOutputStream bos=新的BufferedOutputStream(fout1);
字节[]b=新字节[1024];int i=0,count=0;
而((count=is.read(b))!=-1)
{
bos.write(b,0,count);
i+=计数;
出版进度(一);
Log.v(“信息------------------------------------------”,“”+计数);
}
fout1.close();
}捕获(例外e){
Log.v(“信息-----------------”、“错误!!”;
Log.v(“信息-------------------------------”,例如getMessage());
e、 printStackTrace();
}
返回null;
}
受保护的void onProgressUpdate(整数…进度){
tv.setText(“已下载”+进度[0]+“/”+大小);//tv是一个文本视图
}
}
当我运行应用程序时,下载完成后,计数和大小相同,但实际文件大小(即/mnt/sdcard/xyz.zip)始终小于大小。知道哪里出了问题吗?覆盖onPostExecute并检查它是否真的完成了,也许这里有一段代码可以下载,并提供resume支持, 请注意,因为如果按back,下载可能仍在运行:
if (isCancelled())
return false;
因为套接字上的close()将在退出时挂起,而您不会注意到它,所以需要使用in循环
代码如下:
class DownloaderTask extends AsyncTask<String, Integer, Boolean>
{
private ProgressDialog mProgress;
private Context mContext;
private Long mFileSize;
private Long mDownloaded;
private String mDestFile;
public DownloaderTask(Context context, String path)
{
mContext = context;
mFileSize = 1L;
mDownloaded = 0L;
mDestFile = path;
}
@Override
protected void onPreExecute()
{
mProgress = new ProgressDialog(mContext);
mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgress.setMessage("Downloading...");
mProgress.setCancelable(true);
mProgress.setCanceledOnTouchOutside(false);
mProgress.setOnCancelListener(new DialogInterface.OnCancelListener()
{
@Override
public void onCancel(DialogInterface dialog)
{
DownloaderTask.this.cancel(true);
}
});
mProgress.show();
}
@Override
protected void onProgressUpdate(Integer... percent)
{
mProgress.setProgress(percent[0]);
}
@Override
protected Boolean doInBackground(String... urls)
{
FileOutputStream fos = null;
BufferedInputStream in = null;
BufferedOutputStream out = null;
AndroidHttpClient mClient = AndroidHttpClient.newInstance("AndroidDownloader");
try
{
HttpResponse response = null;
HttpHead head = new HttpHead(urls[0]);
response = mClient.execute(head);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
return false;
Boolean resumable = response.getLastHeader("Accept-Ranges").getValue().equals("bytes");
File file = new File(mDestFile);
mFileSize = (long) Integer.parseInt(response.getLastHeader("Content-Length").getValue());
mDownloaded = file.length();
if (!resumable || (mDownloaded >= mFileSize))
{
Log.e(TAG, "Invalid size / Non resumable - removing file");
file.delete();
mDownloaded = 0L;
}
HttpGet get = new HttpGet(urls[0]);
if (mDownloaded > 0)
{
Log.i(TAG, "Resume download from " + mDownloaded);
get.setHeader("Range", "bytes=" + mDownloaded + "-");
}
response = mClient.execute(get);
if ((response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) && (response.getStatusLine().getStatusCode() != HttpStatus.SC_PARTIAL_CONTENT))
return false;
if (mDownloaded > 0)
publishProgress((int) ((mDownloaded / mFileSize) * 100));
in = new BufferedInputStream(response.getEntity().getContent());
fos = new FileOutputStream(file, true);
out = new BufferedOutputStream(fos);
byte[] buffer = new byte[8192];
int n = 0;
while ((n = in.read(buffer, 0, buffer.length)) != -1)
{
if (isCancelled())
return false;
out.write(buffer, 0, n);
mDownloaded += n;
publishProgress((int) ((mDownloaded / (float) mFileSize) * 100));
}
} catch (Exception e)
{
e.printStackTrace();
return false;
} finally
{
try
{
mClient.close();
if (in != null)
in.close();
if (out != null)
out.close();
if (fos != null)
fos.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
return true;
}
@Override
protected void onCancelled()
{
finish();
}
@Override
protected void onPostExecute(Boolean result)
{
if (mProgress.isShowing())
mProgress.dismiss();
if (result)
// done
else
// error
}
}
类下载任务扩展异步任务
{
私人进程;
私有上下文;
私人长文件大小;
私人长时间下载;
私有字符串mDestFile;
公共下载任务(上下文、字符串路径)
{
mContext=上下文;
mFileSize=1L;
MDownload=0升;
mDestFile=path;
}
@凌驾
受保护的void onPreExecute()
{
mProgress=新建进度对话框(mContext);
mProgress.setProgressStyle(ProgressDialog.STYLE_水平);
设置消息(“下载…”);
mProgress.setCancelable(真);
将进程设置为取消到外部(false);
mProgress.setOnCancelListener(新的DialogInterface.OnCancelListener()
{
@凌驾
public void onCancel(对话框接口对话框)
{
DownloaderTask.this.cancel(true);
}
});
mProgress.show();
}
@凌驾
受保护的void onProgressUpdate(整数…百分比)
{
mProgress.setProgress(百分比[0]);
}
@凌驾
受保护的布尔doInBackground(字符串…URL)
{
FileOutputStream=null;
BufferedInputStream in=null;
BufferedOutputStream out=null;
AndroidHttpClient mClient=AndroidHttpClient.newInstance(“AndroidDownloader”);
尝试
{
HttpResponse响应=null;
HttpHead=新的HttpHead(URL[0]);
响应=mClient.execute(head);
if(response.getStatusLine().getStatusCode()!=HttpStatus.SC\u OK)
返回false;
布尔可恢复=response.getLastHeader(“接受范围”).getValue().equals(“字节”);
文件文件=新文件(mDestFile);
mFileSize=(长)整数.parseInt(response.getLastHeader(“内容长度”).getValue());
mdownload=file.length();
如果(!可恢复| |(MDownload>=mFileSize))
{
Log.e(标记“无效大小/不可恢复-删除文件”);
delete();
MDownload=0升;
}
HttpGet=新的HttpGet(URL[0]);
如果(MDownload>0)
{
Log.i(标签,“从“+mdownload”下载简历);
get.setHeader(“范围”、“字节数=“+mdownload+”-”);
}
response=mClient.execute(get);
如果((response.getStatusLine().getStatusCode()!=HttpStatus.SC_确定)&&(response.getStatusLine().getStatusCode()!=HttpStatus.SC_部分内容))
返回false;
如果(MDownload>0)
出版进度((int)((mdownload/mFileSize)*100);
in=new BufferedInputStream(response.getEntity().getContent());
fos=新文件输出流(文件,真);
out=新的缓冲输出流(fos);
字节[]缓冲区=新字节[8192];
int n=0;
而((n=in.read(buffer,0,buffer.length))!=-1)
{
如果(isCancelled())
返回false;
out.write(缓冲区,0,n);
mdownload+=n;
发布进度((int)((mdownload/(float)mFileSize)*100);
}
}捕获(例外e)
{
e、 printStackTrace();
返回false;
}最后
{
尝试
{
mClient.close();
if(in!=null)
in.close();
if(out!=null)
out.close();
如果(fos!=null)
fos.close();
}捕获(IOE异常)
{