Writing Java codes in terminal is a pain for tons of boilerplate. But sometimes you have to. So we can write groovy instead.
Origin Java codes (Convert.java):
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import org.apache.commons.lang3.StringEscapeUtils;
public class Convert {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("target"));
String line = reader.readLine();
System.out.println("file content: "+line);
String out = StringEscapeUtils.unescapeJava(line);
System.out.println("from string to char: " + out);
String out2 = StringEscapeUtils.escapeJava(out);
System.out.println("from char to string : " + out2);
}
}
$ javac -cp commons-lang3-3.2.1.jar:. Convert.java
$ java -cp commons-lang3-3.2.1.jar:. Convert
Corresponding Groovy codes (convert.groovy):
import org.apache.commons.lang3.StringEscapeUtils
def reader = new BufferedReader(new FileReader("target"))
def line = reader.readLine()
println "file content: $line"
def out = StringEscapeUtils.unescapeJava(line)
println "from string to char: $out"
def out2 = StringEscapeUtils.escapeJava(out)
println "from char to string: $out2"
Run it: groovy -cp commons-lang3-3.2.1.jar convert.groovy
Key points to writing groovy codes:
-
Dynamic type but with "def" (see "http://stackoverflow.com/questions/184002/groovy-whats-the-purpose-of-def-in-def-x-0" for its reason);
-
No need to import Java built-in library;
-
No need to take care of the exceptions;
-
semi-colon at the end of line is optional;
-
Use "println" instead of "System.out.println...";
Ref:
http://stackoverflow.com/questions/764416/why-would-one-use-groovy-over-java