java 如何在java中下载文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4698109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to download a file in java?
提问by Kyle
I've tried a few byte while loop methods and this method below:
我已经尝试了几个字节的 while 循环方法和下面的这个方法:
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();
}
}
}
But the methods just aren't very efficient/fast. I found out about the apache Utils and I'm using
但是这些方法并不是很有效/快速。我发现了 apache Utils 并且我正在使用
IOUtils.copy(new URL("http://ds-forums.com/kyle-tests/uploads/Screenshots.zip").openStream(), new FileOutputStream(System.getProperty("user.home").replace("\", "/") + "/Desktop/Screenshots.zip"));
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)
但这是最好的方法吗?我现在很困惑哪种方法最适合下载 26mb 的压缩文件。(上面的文件只有 1mb 我正在测试方法)
I'm asking just to see if someone else ever ran into this problem and maybe they could help me. Thanks.
我只是想看看其他人是否遇到过这个问题,也许他们可以帮助我。谢谢。
回答by Uriah Carpenter
If you already have Commons IO on the classpath use
如果您已经在类路径上使用了 Commons IO
org.apache.commons.io.FileUtils.copyURLToFile(URL, File)
It takes care of all the stream housekeeping of opening and closing and calling mkdirs on the parent of File.
它负责在 File 的父级上打开和关闭以及调用 mkdirs 的所有流管理。