Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

download zip file using java?

I am downloading zip file from web server using Java but somehow I am loosing about 2kb in each file. I don't know why since same code works fine with other formats, e.g, text, mp3 and extra. any help is appreciated? here is my code.

public void download_zip_file(String save_to) {
    try {
        URLConnection conn = this.url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("content-type", "binary/data");
        InputStream in = conn.getInputStream();
        FileOutputStream out = new FileOutputStream(save_to + "tmp.zip");

        byte[] b = new byte[1024];
        int count;

        while ((count = in.read(b)) > 0) {
            out.write(b, 0, count);
        }
        out.close();
        in.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}
like image 446
Mohamed Avatar asked Apr 16 '10 21:04

Mohamed


People also ask

How do I download a 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 zip file from REST API?

Click the RestAPI folder. Select the RAPI_DOCS. zip file, which is displayed in the right pane of the table. Click Download to save the file.

Which ZIP format is used in Java?

util. zip. ZipOutputStream can be used to compress a file into ZIP format. Since a zip file can contain multiple entries, ZipOutputStream uses java.


2 Answers

It should be as below:

while ((count = in.read(b)) >= 0)

in.read can return 0.

like image 169
Skip Head Avatar answered Oct 21 '22 09:10

Skip Head


Put an out.flush() just after the " while ((count = in.read(b)) > 0) {...}" section and before the out.close().

like image 42
Ray Avatar answered Oct 21 '22 09:10

Ray