I think you need to try regx.
// first convert to string String output = template.toString(); output = output.replaceAll("(?m)^\\s*$[\r\n]+", ""); // here is my regx System.out.println(output);