栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Java Apache Commons下载文件?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Java Apache Commons下载文件?

如果您正在寻找一种在下载之前获取字节总数的方法,则可以从

Content-Length
http响应的标头中获取此值。

如果只需要下载后的最终字节数,则最简单的方法就是检查刚刚写入的文件大小。

但是,如果要显示当前已下载多少字节的进度,则可能需要扩展apache

CountingOutputStream
来包装,
FileOutputStream
以便每次
write
调用方法时,它都会计算通过的字节数并更新进度条。

更新资料

这是的简单实现

DownloadCountingOutputStream
。我不确定您是否熟悉使用
ActionListener
它,但是它对于实现GUI是有用的。

public class DownloadCountingOutputStream extends CountingOutputStream {    private ActionListener listener = null;    public DownloadCountingOutputStream(OutputStream out) {        super(out);    }    public void setListener(ActionListener listener) {        this.listener = listener;    }    @Override    protected void afterWrite(int n) throws IOException {        super.afterWrite(n);        if (listener != null) { listener.actionPerformed(new ActionEvent(this, 0, null));        }    }}

这是用法示例:

public class Downloader {    private static class ProgressListener implements ActionListener {        @Override        public void actionPerformed(ActionEvent e) { // e.getSource() gives you the object of DownloadCountingOutputStream // because you set it in the overriden method, afterWrite(). System.out.println("Downloaded bytes : " + ((DownloadCountingOutputStream) e.getSource()).getByteCount());        }    }    public static void main(String[] args) {        URL dl = null;        File fl = null;        String x = null;        OutputStream os = null;        InputStream is = null;        ProgressListener progressListener = new ProgressListener();        try { fl = new File(System.getProperty("user.home").replace("\", "/") + "/Desktop/Screenshots.zip"); dl = new URL("http://ds-forums.com/kyle-tests/uploads/Screenshots.zip"); os = new FileOutputStream(fl); is = dl.openStream(); DownloadCountingOutputStream dcount = new DownloadCountingOutputStream(os); dcount.setListener(progressListener); // this line give you the total length of source stream as a String. // you may want to convert to integer and store this value to // calculate percentage of the progression. dl.openConnection().getHeaderField("Content-Length"); // begin transfer by writing to dcount, not os. IOUtils.copy(is, dcount);        } catch (Exception e) { System.out.println(e);        } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(is);        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/453650.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号