nerdexam
Oracle

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

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 main(String[] args) throws Exception { String fileName = "file.txt"; String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; ByteBuffer buffer = ByteBuffer.wrap(str.getBytes()); // line 1 fileChannel.write(buffer); fileChannel.close(); } } You want to obtain the FileChannel object on line 1. Which code fragment will make the code compile?

Options

  • Atry (FileChannel fileChannel = new FileOutputStream(fileName).getChannel()) {}
  • Btry (FileChannel fileChannel = new FileOutputStream(new File(fileName)).getChannel()) {}
  • Ctry (FileChannel fileChannel = new FileChannel(new FileOutputStream(fileName))) {}
  • Dtry (FileChannel fileChannel = new FileOutputStream(fileName).getChannel()) {}

How the community answered

(32 responses)
  • A
    72% (23)
  • B
    16% (5)
  • C
    9% (3)
  • D
    3% (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.

Full 1Z0-819 Practice