加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 如何从URL下载(使用http连接)检索文件的大小?

发布时间:2020-12-14 16:46:04 所属栏目:Java 来源:网络整理
导读:我正在使用一个使用http连接下载文件的项目.我在下载过程中显示一个进度条状态的水平进度条. 我的功能如下所示: .......try { InputStream myInput = urlconnect.getInputStream(); BufferedInputStream buffinput = new BufferedInputStream(myInput); Byt
我正在使用一个使用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”,也许这是我要下载的文件数.

Is there any way to figure it out?

更新1

I haven’t got any thread which allow me to figure this out.
Currently I have got a horizontal progress bar whch displays only 0 and 100% whitout intermediate values. I
think about another approach. If I know the rate of my wifi and the
size of the file I can determinate the time of downloading.

I know that I can retrieve the piece of information of my Wifi
connection and the size of my file to download.

Is anybody already have worked or have thread on it?

解决方法

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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读