019-005-010
Resource Management: Closeable File Logger
Medium
Problem Description
Resource Management: Closeable File Logger
In this problem: You will create a FileLogger class that implements the Closeable interface, and use a try-with-resources statement to ensure the resource is properly closed.
Learning Objective: Understand resource management using the Closeable interface and try-with-resources statement
Overview
In Java, resources like files and DB connections must be closed after use. By implementing the Closeable interface and using try-with-resources, close() is guaranteed to be called automatically even when exceptions occur.
Specifications
FileLoggerclass (implementsCloseable)- Constructor: prints
"FileLogger opened" void write(String message): prints"Writing: " + messagevoid close(): prints"FileLogger closed"
- Constructor: prints
Mainclass- Creates
FileLoggerin a try-with-resources statement - Calls
write("Hello") - Calls
write("World") - Prints
"Done"after the try-with-resources block ends
- Creates
Output Format
FileLogger opened
Writing: Hello
Writing: World
FileLogger closed
Done
Ready to Try Running Code?
Log in to access the code editor and execute your solutions for this problem.
Don't have an account?
Sign Up