Vishnu Viswambharan
Vishnu Viswambharan

Reputation: 143

File writing in Java using FileOutputStream

String remoteFile2 = "/test/song.mp3";
            File downloadFile2 = new File("D:/Downloads/song.mp3");
            OutputStream outputStream2 = new BufferedOutputStream(new FileOutputStream(downloadFile2));
            InputStream inputStream = ftpClient.retrieveFileStream(remoteFile2);
            byte[] bytesArray = new byte[4096];
            int bytesRead = -1;
            while ((bytesRead = inputStream.read(bytesArray)) != -1) {
                outputStream2.write(bytesArray, 0, bytesRead);
            }

This is a sample file writing code in java,

byte[] bytesArray = new byte[4096];

In this line what exactly 4096 means, what is the possibility of changing this value?

Upvotes: 0

Views: 1339

Answers (2)

Mạnh Quyết Nguyễn
Mạnh Quyết Nguyễn

Reputation: 18235

When deal with stream, you often read bytes in chunk.

If you read / write byte one by one then there are lots of overhead (like init the array to store the byte, put the byte to stream, remember the current position in file... etc) for each byte.

So if you read a group of bytes, you still have those overhead but lesser (For example if you have 4000 bytes, you have 4000x overhead. But if you read 100 bytes per time, you have 4000/100 = 40x overhead only)

The length of chunk is often choosen to balance between the time to read/write the chunk and the size of chunk.

Its often set to 2k or 4k. Might be related with disk sector (512 bytes, 2048 bytes...)

Upvotes: 1

Naresh Bharadwaj
Naresh Bharadwaj

Reputation: 302

Here 4096 is the buffer size. So whenever you loop is going on it first read 4096 bytes and after that it will go inside the loop.

Upvotes: 0

Related Questions