简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM