Course contentsShow
← Java
Lesson 1974 of 2,87040. File I/O: Character StreamsFree lesson

Writing Characters with write() Methods

Learn FileWriter's write() methods for writing single characters, character arrays, and strings efficiently.

Writing Characters with write() Methods

You'll learn how to use FileWriter's write() methods to output individual characters, character arrays, and complete strings to text files.

The Core Idea

Just as FileReader offers multiple read() methods for different input scenarios, FileWriter provides several write() methods tailored to different output needs. You can write a single character when precision matters, dump entire character arrays for bulk operations, or write strings directly—the most common case in real-world applications.

Think of it like addressing letters: sometimes you write one character at a time (calligraphy), sometimes you stamp a whole line at once (array), and sometimes you just write normal sentences (strings). Each method suits different situations.

The Three write() Variants

write(int c) – Single Character

Writes one character at a time. The int parameter actually holds a char value (0–65535 Unicode range).

FileWriter writer = new FileWriter("output.txt");
writer.write('H');
writer.write('i');
writer.close();

write(char[] cbuf) – Character Array

Writes an entire array of characters in one call—efficient for bulk data.

char[] data = {'H', 'e', 'l', 'l', 'o'};
FileWriter writer = new FileWriter("output.txt");
writer.write(data);
writer.close();

write(String str) – Complete String

The most convenient method for everyday text writing. Writes the entire string directly.

FileWriter writer = new FileWriter("output.txt");
writer.write("Hello, World!");
writer.close();

Choosing the Right Method

  • Use write(int) for character-by-character control
  • Use write(char[]) when working with character buffers
  • Use write(String) for readable, maintainable text output

Key Takeaway: FileWriter's write() methods give you flexibility—write single characters with write(int), bulk data with write(char[]), or readable text with write(String), choosing based on your data source and performance needs.