java apache commons_使用java apache commons下载文件?

如果您正在寻找一种获取下载前总字节数的方法,您可以从http响应中的Content-Length头部获取此值.

如果您只想在下载后的最终字节数,最简单的方法是检查您要写入的文件大小.

但是,如果要显示当前下载的字节的进度,可能需要扩展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);

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值