Writer's Core Methods: write(), write(char[]), and flush()
You'll learn the essential methods for writing character data to destinations and ensuring it actually arrives.
The Core Concept
The Writer class provides three fundamental methods for output operations. write(int) writes a single character (passed as an integer representing the Unicode code point), write(char[]) writes an entire array of characters at once, and flush() forces any buffered data to be written immediately to the destination.
Why Multiple write() Methods?
Just like Reader offered multiple ways to read, Writer mirrors this for output:
write(int c): Writes one character. The int parameter holds the character's Unicode value—only the lower 16 bits are used.write(char[] cbuf): Writes an entire character array efficiently in one operation.write(char[] cbuf, int off, int len): Writes a portion of an array, starting at offsetoffforlencharacters.
The Critical Role of flush()
Think of flush() as forcing a delivery truck to depart immediately, even if it's not completely full. Many Writer implementations use internal buffers for efficiency. Data you "write" may sit in memory temporarily. Calling flush() ensures all pending characters are pushed to the actual destination (file, network, etc.).
When to flush:
- Before closing (though
close()automatically flushes) - When you need immediate visibility (logging, real-time communication)
- After writing critical data that must persist immediately
The Encoding Advantage
Unlike byte streams that write raw bytes, character streams handle encoding automatically. When you write a char[], the underlying implementation converts characters to bytes using the appropriate charset (UTF-8, ISO-8859-1, etc.), shielding you from encoding complexity.
Key Takeaway: Writer provides write() methods for single characters and character arrays, with flush() ensuring buffered data reaches its destination immediately—essential for character-based output with automatic encoding.