Added if (output != null) output.close(); in flush()