Junior — Middle
Каковы основные требования к ресурсам, используемым внутри блока try-with-resources в Java?
sobes.tech AI
Answer from AI
In Java, a resource used within a try-with-resources block must implement the AutoCloseable interface. This guarantees that the close() method will be called automatically after the resource is no longer needed, even if an exception occurs inside the block.
Main requirements:
- The resource class must implement
AutoCloseable(orCloseable, which extendsAutoCloseable). - The
close()method should properly release the resource (e.g., close a file, network connection, etc.).
Example:
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line = br.readLine();
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
In this example, BufferedReader implements Closeable, and its close() method will be called automatically after the try block, releasing the resource.