Why initialize byte array to 1024 while reading or writing a file?

buffer, io, java

Solution

That is called buffering and ,each time you overwrite the contents of the buffer each time you go through the loop.

Simply reading file in chunks, instead of allocating memory for the file content at a time.

Reason behind this to do is you will become a clear victim of OutOfMemoryException if file is too large.

And coming to the specific question, That is need not to be 1024, even you can do with 500. But a minimum 1024 is a common usage.

Problem

In java input or output stream , there always has a byte array size of 1024. Just like below: ``` URL url = new URL(src); URLConnection connection = url.openConnection(); InputStream is = connection.getInputStream(); OutputStream os = new FileOutputStream("D:\\images"+"\\"+getName(src)+getExtension(src)); byte[] byteArray = new byte[1024]; int len = 0; while((len = is.read(byteArray))!= -1){ os.write(byteArray, 0, len); } is.close(); os.close(); ``` Why initialize this array to 1024?

Original source

Related problems