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();
}
}
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.
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.
util. zip. ZipOutputStream can be used to compress a file into ZIP format. Since a zip file can contain multiple entries, ZipOutputStream uses java.
It should be as below:
while ((count = in.read(b)) >= 0)
in.read
can return 0
.
Put an out.flush()
just after the " while ((count = in.read(b)) > 0) {...}
" section and before the out.close()
.
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