A developer needs to write text to a file with UTF-8 encoding. Which class should be used?
This allows explicit UTF-8 encoding for writing text.
Why this answer
Option B is correct because it explicitly constructs an OutputStreamWriter with a FileOutputStream and StandardCharsets.UTF_8, ensuring the text is written with UTF-8 encoding. This is the standard approach when you need precise control over the character encoding, as the OutputStreamWriter acts as a bridge from byte streams to character streams using the specified charset.
Exam trap
The trap here is that candidates often assume FileWriter or BufferedWriter automatically use UTF-8, but they actually rely on the platform's default charset, which may vary across operating systems, leading to encoding bugs in production.
How to eliminate wrong answers
Option A is wrong because BufferedWriter is a character stream that wraps another Writer but does not itself specify encoding; it relies on the underlying Writer's encoding, which by default is the platform's default encoding, not necessarily UTF-8. Option C is wrong because FileWriter uses the platform's default charset (e.g., UTF-8 on some systems, but not guaranteed) and does not allow specifying a charset, making it unreliable for cross-platform UTF-8 requirements. Option D is wrong because PrintWriter with the default constructor writes to System.out and does not write to a file; even if used with a file, it would use the platform's default encoding unless explicitly wrapped with an OutputStreamWriter specifying UTF-8.