如何在java中下载文件?

Kyl*_*yle 6 java apache-commons

我尝试了几个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();
 }
Run Code Online (Sandbox Code Playgroud)

}

但这些方法不是非常有效/快速.我发现了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"));
Run Code Online (Sandbox Code Playgroud)

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

我只想问别人是否遇到过这个问题,也许他们可以帮助我.谢谢.

Uri*_*ter 26

如果你已经在类路径上使用了Commons IO

org.apache.commons.io.FileUtils.copyURLToFile(URL, File)
Run Code Online (Sandbox Code Playgroud)

它负责打开和关闭所有流管理,并在File的父级上调用mkdirs.