Saturday, April 11, 2009

Avoid that next coding migraine!

I discovered that reading some data into an array and dumping the whole array to disk, creates a corrupt file because null indices in the array are written to disk with each invocation of the I/O's write method that receives only the array as the argument. What I mean is this; assuming you have the following code:
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: