views:

304

answers:

6

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

Try to remove the lines:

conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("content-type", "binary/data");
Maurice Perry
did that, and nothing changed.
Mohamed
+2  A: 

It should be:

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

in.read can return 0.

Skip Head
already did that, just same.
Mohamed
Wouldn't matter. If it returns 0, then there's simply nothing to write and thus also no need to write.
BalusC
Yes, it matters. -1 should break the loop and nothing else.
zockman
I agree with zockman. 0 means there's nothing to write on this iteration, not that there is nothing left to write.
Skip Head
A: 

I had a problem with downloading zip files from http once that turned out to be that my downloads included http headers in their beginning, but that made my files a bit larger not smaller, so you probably don't have this problem.

As a side note you might consider using Apache Commons Net for download related apps - it's really great.

Bozhidar Batsov
A: 

A few years ago I remember running into a problem with an old version of Tomcat (5.5.25 for memory) that would cause largish downloads to be truncated. We fixed this by upgrading to a 5.5.27. I also recall the same problem was found and fixed in an early Tomcat 6.0 release.

If this rings any bells for you, take a look at the Tomcat change logs.

Stephen C
A: 

Only zip files, huh? Very odd. Is it from any server, or just this one? If you rename the file (change extension) do you get the same problem? Which bytes are missing? Are you sure it's the last 2K bytes and not some chunk from the middle/etc... ?

Kevin Day
He mentioned 45 mins ago in a question comment that he already got it to work by changing the useragent.
BalusC
well that's odd - I don't see a comment to that effect anywhere in this topic...
Kevin Day
+1  A: 

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

Ray