URL zURL = new URL("http://www.some_server.com/some_zip_file.zip");
InputStream bstream = zURL.openStream();
ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
byte[] buf = new byte[4*1024];
int readByte = 0;
while (((readByte = bstream.read(buf)) != -1)) {
outBuffer.write(buf, 0, readByte);
curSize += readByte;
try {
Thread.sleep(20);
} catch (InterruptedException ex) {
Logger.getLogger(Extractor.class.getName()).log(Level.SEVERE, null, ex);
}
}
FileOutputStream outStr = new FileOutputStream(new File("C:/sample1.zip"));
outStr.write(outBuffer.toByteArray());
The file written to disk in the code above is corrupted even if the actual one downloaded was not, because of this line of the code:
outBuffer.write(buf);which should have been:
outBuffer.write(buf, 0, readByte);So please whenever you read into arrays like that, dump only the valid bytes to disk and not the whole array. This could be any oversight that will cause you headache or migraine. So please avoid that next migraine.
No comments:
Post a Comment