简体   繁体   中英

how to download a file in java?

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();
 }

}

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"));

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.

If you already have Commons IO on the classpath use

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM