Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 725
Kyle Avatar asked Jan 15 '11 05:01

Kyle


People also ask

How can download file in Java?

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.

How do I download a text file in Java?

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.

How do I download a zip file in Java?

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.


1 Answers

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.

like image 134
Uriah Carpenter Avatar answered Nov 15 '22 06:11

Uriah Carpenter