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

Writing Single Bytes with write(int)

Master writing individual bytes using write(int), understanding that only the lower 8 bits are written.

Writing Single Bytes with write(int)

You'll learn how to write individual bytes to a file using FileOutputStream.write(int) and understand why only the lower 8 bits of the integer matter.

How write(int) Works

The write(int) method is your tool for writing bytes one at a time to a FileOutputStream. You might wonder why it takes an int (32 bits) when you're writing bytes (8 bits). Here's the key insight: only the lowest 8 bits of the integer are written to the file. The upper 24 bits are completely ignored.

Why an int Parameter?

Think of it like a postal envelope with multiple address fields, but only the bottom line (your apartment number) gets used. Java uses int for convenience and historical reasons—it's the natural integer type. But when the data hits the file, only the rightmost byte (bits 0-7) survives.

Example in Practice

When you write:

FileOutputStream fos = new FileOutputStream("output.txt");
fos.write(65);    // Writes the byte value 65 (ASCII 'A')
fos.write(321);   // 321 = 0x141, but only 0x41 is written (ASCII 'A')
fos.close();

Both calls write the same byte! 321 in binary is 00000001 01000001, but only the last 8 bits (01000001 = 65) reach the file.

Practical Usage

This method is useful for writing binary data byte-by-byte or when you need precise control over individual byte values. It's straightforward but slower than writing byte arrays for large amounts of data.

Key Takeaway: write(int) writes exactly one byte by using only the lower 8 bits of the integer argument; the upper 24 bits are silently discarded, making values 0-255 and their higher equivalents (like 256, 257) wrap around.