Which TWO approaches are valid for writing text data to a file in Java? (Choose two.)
Trap 1: new FileOutputStream("out.txt").write(text.getBytes())
FileOutputStream.write(byte[]) writes raw bytes, not text with proper encoding, so it's not a valid text-writing approach.
Trap 2: new RandomAccessFile("out.txt", "rw").writeUTF(text)
RandomAccessFile.writeUTF writes a string in modified UTF-8 format, which is not a standard text file format.
Trap 3: Files.write(Paths.get("out.txt"), lines, StandardOpenOption.CREATE)
Files.write expects an Iterable of lines (e.g., List<String>), so it's not suitable for writing a single text string without wrapping it in a collection.
- A
new FileOutputStream("out.txt").write(text.getBytes())
Why wrong: FileOutputStream.write(byte[]) writes raw bytes, not text with proper encoding, so it's not a valid text-writing approach.
- B
new RandomAccessFile("out.txt", "rw").writeUTF(text)
Why wrong: RandomAccessFile.writeUTF writes a string in modified UTF-8 format, which is not a standard text file format.
- C
new FileWriter("out.txt", true).write(text)
Correct. FileWriter is a character stream that writes text directly; the true parameter enables append mode.
- D
new PrintWriter("out.txt").print(text)
Correct. PrintWriter has constructors that accept a String filename (or File), and print() writes the text to the file.
- E
Files.write(Paths.get("out.txt"), lines, StandardOpenOption.CREATE)
Why wrong: Files.write expects an Iterable of lines (e.g., List<String>), so it's not suitable for writing a single text string without wrapping it in a collection.