一丶命令行
ProcessBuilder processBuilder = new ProcessBuilder("ipconfig");
processBuilder.redirectErrorStream(true);
try {
Process start = processBuilder.start();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(start.getInputStream(), "GBK"));
StringBuilder builder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line).append("\n");
}
System.out.println(builder);
} catch (Exception e) {
e.printStackTrace();
}
二丶Groovy脚本
public static void main(String[] args) {
testJava();
testScript();
testFileScript();
}
private static void testJava() {
String java = "import com.example.cachedemo.GroovyDemo;" +
"public class Test {" +
"public static boolean test(){return GroovyDemo.test();}" +
"}";
GroovyClassLoader classLoader = new GroovyClassLoader();
Class aClass = classLoader.parseClass(java);
System.out.println(aClass);
try {
Method testMethod = aClass.getMethod("test");
Object invoke = testMethod.invoke(aClass);
System.out.println(invoke);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void testScript() {
Binding binding = new Binding();
binding.setProperty("c", "property");
GroovyShell groovyShell = new GroovyShell(binding);
Object evaluate = groovyShell.evaluate("println 'aaa'\n" +
"\"$c\"");
System.out.println(evaluate);
groovyShell.evaluate("def name = 1g\n" +
"assert name instanceof BigInteger");
groovyShell.evaluate("def test = {println it}\n" +
"test('aaa')");
}
GroovyShell shell = new GroovyShell()
println "$a"
return [c:"1", d: "2"]
private static void testFileScript() {
try {
GroovyScriptEngine scriptEngine = new GroovyScriptEngine("C:\\tmp\\groovy");
Binding binding = new Binding();
while (true) {
binding.setVariable("a", 1);
binding.setVariable("b", 2);
Object run = scriptEngine.run("hello.groovy", binding);
System.out.println(run);
Thread.sleep(5000);
}
} catch (Exception e) {
e.printStackTrace();
}
}