Here is code in Scala:
def write() = {
try {
val out = new PrintWriter(new BufferedWriter(new FileWriter(fileName, true)))
out.println(\"123\")
This is what I use to manage closable resources passed to function returning and not retuning futures
def withClosable[ T, C <: Closeable ]( closable: C )( f: C ⇒ T ) = try { f( closable ) } finally { IOUtils closeQuietly closable }
def withFutureClosable[ T <: Future[Any], C <: Closeable ]( closable: C )( f: C ⇒ T ) = f( closable ) andThen {
case _ => IOUtils closeQuietly closable
}
}
I use IOUtils
from commons-io
to simplify the call to actually close the resource. A simple try { closable.close() } catch { case _ => /* blah */ }
would do
Example usage:
withClosable(new FileInpustream("f")) { stream => /* read the stream */ }