Search code examples
groovyfilehandle

Unclosed file handle when filtering file lines


I've noticed that following code snippet in Groovy lefts unclosed file handle in JVM. I cannot remove this file until GC runs and closes resource by invoking finalizer.

StringWriter writer = new StringWriter()
new File("file.txt").filterLine(writer) { it.startsWith("a") }
println writer.toString()

How to properly close the file when filtering its lines?


Solution

  • filterLine works on a reader too, so you can do:

    StringWriter writer = new StringWriter()
    new File("file.txt").withReader { r ->
       r.filterLine(writer) { it.startsWith("a") }
    }
    println writer.toString()
    

    withReader closes the reader afterwards