6

I have got a little question about buffer size in Java. Why do we set buffer size to 1024 or 2^n. For example:

    inputStream = file.getInputStream();
    File newFile = new File("C:/uploads/operators.xml");
    outputStream = new FileOutputStream(newFile);
    int read = 0;

    byte[] bytes = new byte[1024];
    while ((read = inputStream.read(bytes)) != -1) {
        outputStream.write(bytes, 0, read);
    }
    outputStream.close();
    inputStream.close();

How outputStream.write(bytes, 0, read); works? Why do we use bytes array?

Tony
  • 3,605
  • 14
  • 52
  • 84

2 Answers2

2

To avoid wasting hit to file system, byte sizes should be a multiple of file system sector size (e.g. 512 bytes).

Same applies to CPU L1 cache. Most Intel 486 CPUs has 1K L1 cache, thus the value 1024. Pentium CPUs have at least 8K L1 cache, thus 8 * 1024 is also often used.

Recent file systems have a sector size of 4K and recent CPUs have at least 64K L1 Cache, thus 64 * 1024 is also a choice.

weakish
  • 28,682
  • 5
  • 48
  • 60
  • This answers more of the question correctly. In reality, the file system doesn't read or write one byte at a time. It moves blocks of bytes at a time. I'm attempting to recall when I read about this awhile ago and so may be incorrect but I believe if you chose a buffer size of `508` and the system was moving `512` bytes at a time, the four bytes you tried to save would not be used by the file system anyway. – Steve May 24 '17 at 19:03
1

You read bytes length of bytes.length from file stream and stores them in the byte array bytes[]. And then you write bytes in outputStreem form bytes[] array. For more read the Java I/O documentation.

Anton Dozortsev
  • 4,782
  • 5
  • 34
  • 69