微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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”,也许这是我要下载的文件数.

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

原文地址:https://www.jb51.cc/java/124402.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐