Writing Byte Arrays with write(byte[])
You'll learn how to efficiently write entire byte arrays or array ranges to output streams in a single operation.
The Core Idea
While write(int) writes one byte at a time (which we covered in the previous lesson), write(byte[]) and its cousin write(byte[], offset, length) let you write multiple bytes in one go. Think of it like the difference between carrying groceries one item at a time versus loading them all into a bag and carrying the whole bag at once—much more efficient!
Writing an Entire Byte Array
The write(byte[]) method takes a byte array and writes all its contents to the output stream:
FileOutputStream fos = new FileOutputStream("output.bin");
byte[] data = {65, 66, 67, 68, 69}; // ASCII for "ABCDE"
fos.write(data); // Writes all 5 bytes in one operation
fos.close();
This is significantly faster than looping through the array and calling write(int) for each byte individually.
Writing a Portion of an Array
The write(byte[], int offset, int length) method gives you fine-grained control, allowing you to write only part of an array:
FileOutputStream fos = new FileOutputStream("partial.bin");
byte[] buffer = {10, 20, 30, 40, 50, 60};
fos.write(buffer, 2, 3); // Writes bytes at index 2, 3, 4 (values 30, 40, 50)
fos.close();
The offset parameter specifies where to start reading from the array, and length specifies how many bytes to write.
Why This Matters
Batch writing reduces system calls and dramatically improves performance, especially when dealing with large amounts of data. You'll use this constantly when copying files, writing binary data, or converting data structures to byte representations.
Key Takeaway: Use write(byte[]) to write entire arrays efficiently, or write(byte[], offset, length) when you need to write only a portion of a buffer—both are far more performant than writing bytes one at a time.