Saturday, October 11, 2014

Groovy Enum Generator Using eachLine and String Interpolation

This is a very short example about how to process a file line by line in the Groovy programming language to create an enum. There are so many times I open up the Groovy console to get something done fast. In this example I use the groovy to open up a file, iterate over each line, and use string interpolation to create the output that is then copied into my enum Java file from the contents of a text file.


Code:

def tmpFile = new File("/Users/dbell/Desktop/example.txt")
def cnt = 0
def enumName = "Sports"
def enumStringBuilder = new StringBuilder()
enumStringBuilder.append("public enum ${enumName} {\n\n")
tmpFile.eachLine {
    def desc = it
    def code = desc.toUpperCase().replaceAll("\\s", "_")
    if (cnt > 0) { enumStringBuilder.append(",\n") }
    enumStringBuilder.append("\t${code}(\"${code}\",\"${desc}\")")
    cnt++
}

def enumOutput = enumStringBuilder.toString() + ";\n";
println enumOutput

println "\tString code;"
println "\tString description;\n"
println "\t${enumName}(String code, String description) {"
println "\t\tthis.code = code;"
println "\t\tthis.description = description;"
println "\t}"
println "}"


example.txt

Soccer
Football
Basketball
Hockey
Hacky Sack
Corn Hole


Generated Output

public enum Sports {

SOCCER("SOCCER","Soccer"),
FOOTBALL("FOOTBALL","Football"),
BASKETBALL("BASKETBALL","Basketball"),
HOCKEY("HOCKEY","Hockey"),
HACKY_SACK("HACKY_SACK","Hacky Sack"),
CORN_HOLE("CORN_HOLE","Corn Hole");

String code;
String description;

Sports(String code, String description) {
this.code = code;
this.description = description;
}
}


Screenshot:


No comments:

Post a Comment