Course contentsShow
← Java
Lesson 1926 of 2,87039. File I/O: Basic Byte StreamsFree lesson

Writing Byte Arrays with write(byte[])

Learn to write entire byte arrays efficiently using write(byte[]) and write(byte[], offset, length).

Writing Byte Arrays with write(byte[])

You'll learn how to write entire byte arrays efficiently to output streams in a single operation, significantly improving performance over byte-by-byte writes.

The Core Idea

When you have multiple bytes to write (like file content or buffered data), calling write(int) repeatedly for each byte is inefficient—imagine mailing 100 letters one at a time instead of dropping them all in the mailbox together. The write(byte[]) method lets you write an entire array of bytes in one operation, and write(byte[], int offset, int length) gives you control over which portion of the array to write.

Using write(byte[])

This method writes all bytes from the array to the output stream:

FileOutputStream fos = new FileOutputStream("output.dat");
byte[] data = {65, 66, 67, 68, 69}; // A, B, C, D, E
fos.write(data); // Writes all 5 bytes at once
fos.close();

Much faster than calling write(65), write(66), etc.

Using write(byte[], int offset, int length)

This variant writes only a specific portion of the array:

FileOutputStream fos = new FileOutputStream("partial.dat");
byte[] buffer = {10, 20, 30, 40, 50, 60};
fos.write(buffer, 2, 3); // Writes bytes at indices 2, 3, 4 (values 30, 40, 50)
fos.close();

The offset specifies where in the array to start, and length specifies how many bytes to write.

Why This Matters

Batch writing reduces system calls and I/O overhead. When copying files or processing buffered data, you'll typically read chunks into a byte array and then write those chunks, making these methods essential for performance.

Key Takeaway: Use write(byte[]) to write entire byte arrays efficiently, and write(byte[], offset, length) when you need to write only a specific portion of an array—both methods dramatically outperform byte-by-byte writes.