22 November 2010

Never uses "OutputStream.write(byte[])"

Alslamoa Alykom folks,

Today I am gonna talking about very important IO note, I saw some people usually fail to notice!

Well, the problem here is, when you use a buffer to fill in some OutputStream, you usually write the latest buffer as is with some invalid data (from last value of the buffer).

See the following example:

FileInputStream fis = new FileInputStream("D:/tmp/some_long_file.txt");    // some long file
ByteArrayOutputStream baos = new ByteArrayOutputStream();

byte[] buffer = new byte[1024]; // if you have a small file, try to reduce the value here to notice the output
int i;

while ((i = fis.read(buffer)) != -1)
baos.write(buffer, 0, i); //never use: baos.write(buffer);

fis.close();
baos.close();

// notice the ouput of this line:
System.out.println(baos.toString());


Notice, if you uses baos.write(buffer) instead of the one that takes off-site and size you will have the OutputStream contains corrupted data!
Post a Comment