How to upload a file in java?

I tried several bytes with loop methods and this method is 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 are simply not very efficient / fast. I found out about Apache Utils and I use

 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 this the best method? I am so confused right now which method is best for downloading a zipped 26mb file. (The file above is just 1mb, which I'm testing)

I only ask to see if anyone else has encountered this problem, and maybe they can help me. Thank.

+5
source share
1 answer

If you already have Commons IO on the way to classes, use

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

It takes care of all the threads associated with opening and closing, and calls mkdirs on the parent file.

+21
source

All Articles