1Z0-819 · Question #188
Given: import java.io.File; import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.Arrays; public class Test { public static void…
The correct answer is A. `try (FileChannel fileChannel = new FileOutputStream(fileName).getChannel()) {}`. Option A is correct because FileOutputStream has a constructor that accepts a String filename directly, and calling .getChannel() on it returns a valid FileChannel - this is the standard Java idiom for obtaining a FileChannel for file writing. Option C is the clearest wrong…
Question
FileChannel object on line 1. Which code fragment will make the code compile?Options
- A
try (FileChannel fileChannel = new FileOutputStream(fileName).getChannel()) {} - B
try (FileChannel fileChannel = new FileOutputStream(new File(fileName)).getChannel()) {} - C
try (FileChannel fileChannel = new FileChannel(new FileOutputStream(fileName))) {} - D
try (FileChannel fileChannel = new FileOutputStream(fileName).getChannel()) {}
How the community answered
(32 responses)- A72% (23)
- B16% (5)
- C9% (3)
- D3% (1)
Explanation
Option A is correct because FileOutputStream has a constructor that accepts a String filename directly, and calling .getChannel() on it returns a valid FileChannel - this is the standard Java idiom for obtaining a FileChannel for file writing.
Option C is the clearest wrong answer: FileChannel is an abstract class and cannot be instantiated with new FileChannel(...) - this causes a compile error regardless of arguments passed.
Options A and D appear identical as transcribed, suggesting a likely typo in the question; if D differs subtly in the original (e.g., missing a parenthesis or using incorrect syntax), it would fail to compile.
Option B is syntactically valid (new FileOutputStream(new File(fileName)) compiles fine), so if it appears as a distractor in the original, the distinguishing point may be scope - all try (... ) {} forms with an empty body would leave fileChannel out of scope for the subsequent write and close calls; the real-world fix is to put those calls inside the try block.
Memory tip: Think of it as a chain - FileOutputStream is your bridge to the file system, and .getChannel() is how you "upgrade" to NIO. If you ever see new FileChannel(...) directly, it's a trap - abstract classes can't be new'd.
Community Discussion
No community discussion yet for this question.