Use try-with-resources where appropriate

This is more succinct and idiomatic Java style.