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

查看:32
本文介绍了如何在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天全站免登陆