Make java 1.6 compatible

It was mostly Yifan's change, which I cherry-picked on top of the newest master, and closed the output stream properly after try block.