Question 1
Q1A developer is tasked with creating a method that accepts a java.nio.file.Path object and returns a java.io.BufferedReader for that file. The method must ensure that the file's resources are automatically closed, even if an IOException occurs during reading. Which implementation correctly and most concisely achieves this?
Show answer & explanation
Correct answer: C
The try-with-resources statement is designed for this exact purpose. However, returning the resource from within the try block is problematic because the resource will be closed before the caller can use it. The correct approach is to use a method that returns the stream and rely on the caller to manage its lifecycle, or to perform the reading within the block itself. Given the options, this is a trick question about the scope of try-with-resources. The most correct pattern is not returning the resource, but if forced to choose from flawed options that attempt to solve the problem, the question intent is likely about recognizing the try-with-resources syntax. Correction: The question asks for an implementation that returns a reader. A better implementation would pass a Consumer to process the reader's contents inside the try-with-resources block. However, amongst the given choices, the question is flawed. The most plausible intended answer is the one using Files.newBufferedReader directly, but it must be understood that the resource management is now the caller's responsibility. Let's re-evaluate the question. The question is testing the Files.newBufferedReader method combined with try-with-resources. The only syntactically valid option that uses the modern java.nio.file API and addresses resource management is the one using Files.newBufferedReader. The correct way to use it is to pass the reader to a consumer inside the block. But if the goal is to return it, the try-with-resources block cannot be used in the method itself. The best option among the choices that directly addresses the prompt is to simply return the result of Files.newBufferedReader(p), and document that the caller must close it. Let's assume the question is flawed and seeks the most modern API usage. The factory method Files.newBufferedReader(p) is the most direct way to get a BufferedReader from a Path.