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

  • FileLogger class (implements Closeable)
    • Constructor: prints "FileLogger opened"
    • void write(String message): prints "Writing: " + message
    • void close(): prints "FileLogger closed"
  • Main class
    • Creates FileLogger in a try-with-resources statement
    • Calls write("Hello")
    • Calls write("World")
    • Prints "Done" after the try-with-resources block ends

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