java – 如何从URL下载(使用http连接)检索文件的大小?
我正在使用一个使用http连接下载文件的项目.我在下载过程中显示一个进度条状态的水平进度条.
我的功能如下所示: ....... try { InputStream myInput = urlconnect.getInputStream(); BufferedInputStream buffinput = new BufferedInputStream(myInput); ByteArrayBuffer baf = new ByteArrayBuffer(capacity); int current = 0; while((current = buffinput.read()) != -1) { baf.append((byte) current); } File outputfile = new File(createRepertory(app,0),Filename); FileOutputStream myOutPut = new FileOutputStream(outputfile); myOutPut.write(baf.toByteArray()); ... } 我提前知道我的文件的大小,所以我需要检索的大小在下载(在我的while块).因此,我可以确定进度条的状态. progressBarStatus = ((int) downloadFileHttp(url,app) * 100)/sizefile; 长的downloadFileHttp(..,..)是我的函数的名字. 我已经尝试通过使用outputfile.length来检索它,但是他的值为“1”,也许这是我要下载的文件数.
更新1
解决方法
AsyncTask可能是您的完美解决方案:
private class DownloadFileTask extends AsyncTask<URL,Integer,Long> { protected Long doInBackground(URL... urls) { Url url = urls[0]; //connect to url here ....... try { InputStream myInput = urlconnect.getInputStream(); BufferedInputStream buffinput = new BufferedInputStream(myInput); ByteArrayBuffer baf = new ByteArrayBuffer(capacity); int current = 0; while((current = buffinput.read()) != -1) { baf.append((byte) current); //here you can send data to onProgressUpdate publishProgress((int) (((float)baf.length()/ (float)sizefile) * 100)); } File outputfile = new File(createRepertory(app,Filename); FileOutputStream myOutPut = new FileOutputStream(outputfile); myOutPut.write(baf.toByteArray()); ... } protected void onProgressUpdate(Integer... progress) { //here you can set progress bar in UI thread progressBarStatus = progress; } } 在您的方法中启动AsyncTask调用 new DownloadFileTask().execute(url); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |