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.
We can use java. net. URL openStream() method to download file from URL in java program. We can use Java NIO Channels or Java IO InputStream to read data from the URL open stream and then save it to file.
We will use the copy(inputStream, fileOS) method to download a file into the local system. InputStream inputStream = new URL("http://example.com/my-file-path.txt").openStream(); FileOutputStream fileOS = new FileOutputStream("/Users/username/Documents/file_name. txt"); int i = IOUtils.
In order to download a zip file in Java, we need to firstly set the content type of the HTTP response as “application/zip” and then write the zip file to the ServletOutputStream.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With