如何在Java中下载文件? [英] how to download a file in java?

查看:87
本文介绍了如何在Java中下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了一些字节的while循环方法,下面是该方法:

I've tried a few byte while loop methods and this method below:

try {
     URL dl = null;
     dl = new URL("http://ds-forums.com/kyle-tests/uploads/Screenshots.zip");
     ReadableByteChannel rbc = Channels.newChannel(dl.openStream());
     FileOutputStream fos = new FileOutputStream(fileName + "Screenshots.zip");
     fos.getChannel().transferFrom(rbc, 0, 1 << 24);
     System.out.println(fos.getChannel().size());
     fos.close();
     rbc.close();
 } catch (Exception e) {
     e.printStackTrace();
 }

}

但是这些方法不是非常有效/快速.我发现了有关Apache Utils的信息,并且正在使用

But the methods just aren't very efficient/fast. I found out about the apache Utils and I'm using

 IOUtils.copy(new URL("http://ds-forums.com/kyle-tests/uploads/Screenshots.zip").openStream(), new FileOutputStream(System.getProperty("user.home").replace("\\", "/") + "/Desktop/Screenshots.zip"));

但这是最好的方法吗?我现在很困惑,哪种方法最适合下载26mb的压缩文件. (我正在测试的方法,上面的文件只有1mb)

but is that the best method? I'm so confused right now which method is best for downloading a zipped file 26mb. (The file above is only 1mb I'm testing methods)

我要问的是看看是否有人遇到过这个问题,也许他们可以帮助我.谢谢.

I'm asking just to see if someone else ever ran into this problem and maybe they could help me. Thanks.

推荐答案

如果您已经在类路径上使用了Commons IO,请使用

If you already have Commons IO on the classpath use

org.apache.commons.io.FileUtils.copyURLToFile(URL, File)

它负责在File的父级上打开和关闭以及调用mkdirs的所有流内务处理.

It takes care of all the stream housekeeping of opening and closing and calling mkdirs on the parent of File.

这篇关于如何在Java中下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆