Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

io

buffer

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?

like image 558
Brutal_JL Avatar asked Dec 23 '13 07:12

Brutal_JL


People also ask

Why do we use byte array?

The crucial thing about a byte array is that it gives indexed (fast), precise, raw access to each 8-bit value being stored in that part of memory, and you can operate on those bytes to control every single bit.

Which function is used to write an array of bytes into a file?

Convert byte[] array to File using Java In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class.

Why do we use byte array in Java?

Byte and char arrays are often used in Java to temporarily store data internally in an application. As such arrays are also a common source or destination of data. You may also prefer to load a file into an array, if you need to access the contents of that file a lot while the program is running.


1 Answers

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.

like image 141
Suresh Atta Avatar answered Oct 10 '22 07:10

Suresh Atta