The write(byte[]) and write(byte[], int, int) Methods
You'll learn how to efficiently write multiple bytes at once using byte arrays, with control over exactly which portion of the array to write.
Writing Byte Arrays Efficiently
In the previous lesson, you learned about write(int) for writing a single byte at a time. But what if you have an entire byte array ready to write? Calling write(int) in a loop would be inefficient. Java's OutputStream provides two methods for batch writing:
write(byte[] b)
This method writes all bytes from the provided array to the output stream:
byte[] data = {65, 66, 67, 68}; // A, B, C, D
outputStream.write(data); // Writes all 4 bytes
Think of this as pouring an entire bucket of water at once, rather than transferring it one cup at a time.
write(byte[] b, int off, int len)
This method gives you precise control, writing only a specific portion of the array:
b: the byte array sourceoff: the starting index (offset) in the arraylen: how many bytes to write
byte[] data = {65, 66, 67, 68, 69, 70}; // A through F
outputStream.write(data, 2, 3); // Writes only C, D, E (starting at index 2, writing 3 bytes)
This is like having a large bucket but only pouring out the middle portion—perfect when you're reusing a buffer or only want to write partial data.
Why This Matters
These methods are significantly faster than looping with write(int) because they reduce the number of method calls and allow the stream to optimize internal buffering.
Key Takeaway: Use write(byte[]) to write entire arrays efficiently, and write(byte[], int, int) when you need to write only a specific slice of your byte array—both are much faster than writing bytes one at a time.