I found a groovy introduction in website , paste here :
1 groovyConsole和helloworld
在groovy安裝目錄的bin文件夾下,有一個groovyConsole.sh(windows是groovyConsole.exe), 它就是自帶的簡易groovy程序編輯器. 打開它,輸入如下代碼:
def str1 = "Hello,world.";
println(str1)
String str2 = "Hello,Groovy.";
println(str2)
str3 = "Hello,variables.";
println(str3)
def age1 = 30;
println("You age: "+age1);
age2 = 31;
println("You age: "+age2);
def s = """
知識點:
1>可以用多種方式定義變量
2>如何在控製台輸出文本
3>如何方便的顯示多行文本
"""
println(s);
保存文件,快捷鍵ctrl+R, 恭喜你,第一個groovy程序運行成功.
2 如何定義函數
def func(a,b){
println("Your name is: "+a+" and your age is: " + b);
}
func("Diego",30)
def func1(a,b=25){
if(b==null){
println("Your name is: "+a+" and your age is a secret");
}else{
println("Your name is: "+a+" and your age is: " + b);
}
}
func1("Diego")
func1("Diego",30)
func1("Diego",null)
/**
知識點:
1>如何定義和函數
2>如何在函數裏定義默認參數
**/
3 字符串使用
def country="南非"
def stringTemplate(country){
return "${country}世界杯來了";
}
def s = stringTemplate(country);
println(s+",length: "+s.length());
println("Country is: "+s[0,2]);
println("Country is: "+s.substring(0,2));
def greetingWithFormat = """
歡迎來到${country}
6.11-7.11, 世界杯將會激情展開!
""";
println(greetingWithFormat);
/**
知識點:
1>模板式字符串,這是個很好很強大的功能.
2>如何多段式風格字符串.
3>如何用groovy的風格完成substring功能.
4>中文字符串長度
**/
4 List的使用
def myrange = 25 .. 10
println(myrange);
myrange = 11 .. 19
println(myrange);
println("First element of collection is: "+myrange[0]);
//myrange<<</span>20;//This statement will cause exception.
println("Last element of collection is: "+myrange[-1]);
println("Sub collection: " + myrange[2,5]);
println("Reverse: " + myrange.reverse());
println("Remove element: " + (myrange - 18));
println("Remove sub collection: " + (myrange - [12,13,14,15]));
//==================
def coll = ["C","C++","Java","JavaScript","Python"]
println("Program anguages you're knowing: "+coll);
coll <<</span> "Groovy" // It's == coll.add("Groovy")
println("Now you're learning: " + coll[-1])
//cool syntax
coll = coll*.toUpperCase()
println(coll);
/**
知識點:
1>如何方便定義collection
2>collection的各種操作
3>注意groovy重載了+和-運算符. 所以collection可以很方便的用+和-刪除元素. 在這樣做的時候, 最好加上().
4>*是很酷的一個功能, 方便的遍曆集合元素.
**/
5 方便的for循環
//For statement
def forFunc(a,repeat=10){
for(i=a;irepeat;i++){
print(i+",");
}
}
def forFunc1(a,repeat=10){
for(i in a .. repeat){
print(i+",");
}
}
forFunc(2);
println();
forFunc1(2);
/**
知識點:
1>兩種循環風格.
2>a .. repeat 這種風格等價於 i=a;i<=repeat;i++
**/
6 方便的for循環
//For statement
def forFunc(a,repeat=10){
for(i=a;irepeat;i++){
print(i+",");
}
}
def forFunc1(a,repeat=10){
for(i in a .. repeat){
print(i+",");
}
}
forFunc(2);
println();
forFunc1(2);
/**
知識點:
1>兩種循環風格.
2>a .. repeat 這種風格等價於 i=a;i<=repeat;i++
**/
7 map的用法
def mymap = ["name":"Diego",age:30,hobbies:["Football","Reading","Bible"]]
println("Your name is "+ mymap["name"] +" ,age is "+mymap["age"]+" ,hobbies: " + mymap["hobbies"]);
//add element
mymap.location = "Shenzhen"
println(mymap);
//loop map by closure.
mymap.each{key,value->
println("Key: "+key+",value: "+value);
}
/**
知識點:
1>如何使用map
2>如何遍曆map
**/
8 closure的用法
//Traditional looping collection.
def mydata = ["Java","Groovy","JavaScript"]
def printUpperCase(a){
println(a.toUpperCase());
}
for (i in 0..2){
printUpperCase(mydata[i]);
}
println("use closure=====================");
mydata.each{
println(it.toUpperCase());
}
println("def closure=====================");
def myclosure = {myvar->
println(myvar.toUpperCase());
}
mydata.each(myclosure);
println("closure and map=====================");
def mymap = ["name":"Diego",age:30,hobbies:["Football","Reading","Bible"]]
mymap.each{key,value->
println("key is: "+key+" and value is: " + value);
}
println("closure and string=====================");
def mystring= "Diego"
mystring.each{s->
print(s+",");
}
/**
知識點:
1>閉包(closure)的直觀例子
2>如果沒有特別聲明, 閉包將用it作為變量名字
3>如何定義和調用閉包,如何在閉包自定義變量名字
**/
9 文件操作
BufferedReader reader = new File('f:/abc.txt').newReader('GBK')
BufferedWriter writer = new File('f:/abc.csv').newWriter('UTF-8')
reader.eachLine { line ->
if(line && line[0] != '#') {
writer.writeLine(line)
}
}
writer.close()
def createFile(path,createIfNotExist){
def file = new File(path);
if( !file.exists() ){
if(createIfNotExist){
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
file.createNewFile();
}else{
throw NullPointerException("Missing file: "+path);
}
}
return file;
}
def copyFile(String frompath,String topath,boolean createDestIfNotExist){
def fromfile = new File(frompath);
if( !fromfile.exists()){
println(" ###################Missing file: " + fromfile+"n");
return false;
}else{
println(" Copying file: " + frompath+"n");
}
def tofile = createFile(topath,createDestIfNotExist);
tofile.withWriter { file ->
fromfile.eachLine { line ->
file.writeLine(line)
}
}
return true;
}
/**
知識點
1>如何讀寫文件
2>groovy的文件操作
**/
10 讀寫xml
特別提示: 根據自己的實際情況修改文件路徑.
def sample =
""" We'll create this xml:
"""println(sample);
//寫xml
testxml =
"g:/download/test.xml";
import groovy.xml.MarkupBuilder
xml = new MarkupBuilder(new FileWriter(testxml));
xml.beans{
bean(id:
"myBean1",
class:
"com.diegochen.Bean1"){
property(name:
"dao",ref:
"dao1")
}
bean(id:
"myBean2",
class:
"com.diegochen.Bean2"){
property(name:
"dao",ref:
"dao2")
}
}
println(
"Done creation. Now reading xmln")
//Read xml
start =System.currentTimeMillis();//傳說XmlParser吃內存,XmlSlurper速度慢
def node = new XmlParser().parse(new File(testxml))
println(
"node name:"+node.name());//取得node的名字.為什麽不是getname()???? 命名規則真混亂
end =System.currentTimeMillis();
println(
"elapsed time: "+ (end-start)+
" ms");
/**
node = new XmlSlurper().parse(new File(testxml))
println(
"node name:"+node.name());
end =System.currentTimeMillis();
println(
"elapsed time: "+ (end-start)+
" ms");
**/
//訪問子節點和屬性
println(
"How many beans?: "+node.children().size());
def bean2 = node.children()[1];
println(
"2nd bean's id: "+bean2.
"@id");
println(
"2nd bean's class: "+bean2.
"@class");
println(
"2nd bean's dao property: "+bean2.children()[0].
"@ref");
/**
知識點:
1>怎樣生成xml
2>怎樣讀xml
**/
11 讀配置文件
先創建一個名為config.gy的配置文件. 內容如下:
path{
//This is file update list txt path. The file should contain a batch of file path.
file_update_list = "e:/work/cc2/file_update_list.txt";
//This is root directory of workspace
workspace_root_path = "e:/work/cc2/asia_stratagy/workspace";
//This is directory for backup.
backup_path = "d:/download";
}
//Don't modify below config!!!
constants{
debug = "Y"
}
然後在另一個groovy文件裏如此訪問
def propfile = "${System.properties['user.dir']}/config.gy";
println("--config file: "+propfile);
def config = new ConfigSlurper().parse( new File( propfile ).toURL()) ;
def fileUpdateList = config.path.file_update_list;
def workspace_root_path = config.path.workspace_root_path;
def backup_path = config.path.backup_path;
def debugFlag = config.constants.debug;
if(debugFlag == "Y"){
println("config:==[fileUpdateList] : "+ fileUpdateList );
println("config:==[workspace_root_path] : "+ workspace_root_path );
println("config:==[backup_path] : "+ backup_path );
println("config:==[debugFlag] : "+ debugFlag );
}