Groovy注釋標(biāo)記和Java一樣捌朴,支持//或者/**/
Groovy語(yǔ)句可以不用分號(hào)結(jié)尾
Groovy中支持動(dòng)態(tài)類(lèi)型,即定義變量的時(shí)候可以不指定其類(lèi)型。Groovy中惩淳,變量定義可以使用關(guān)鍵字def辣恋。注意咆繁,雖然def不是必須的淳梦,但是為了代碼清晰甘邀,建議還是使用def關(guān)鍵字
def variable1 = 1 //可以不使用分號(hào)結(jié)尾
def varable2 = "I ama person"
int y =1 //變量定義時(shí)琅攘,也可以直接指定類(lèi)型
def int x = 1
variable=1 //**不是用def就是全局變量,使用def是局部變量
函數(shù)定義時(shí)松邪,參數(shù)的類(lèi)型也可以不指定坞琴。比如
String testFunction(arg1,arg2){//無(wú)需指定參數(shù)類(lèi)型
...
}
除了變量定義可以不指定類(lèi)型外,Groovy中函數(shù)的返回值也可以是無(wú)類(lèi)型的逗抑。比如:
//無(wú)類(lèi)型的函數(shù)定義剧辐,必須使用def關(guān)鍵字
def nonReturnTypeFunc(){
last_line //最后一行代碼的執(zhí)行結(jié)果就是本函數(shù)的返回值
}
//如果指定了函數(shù)返回類(lèi)型寒亥,則可不必加def關(guān)鍵字來(lái)定義函數(shù)
String getString(){
return"I am a string"
}
函數(shù)返回值:Groovy的函數(shù)里,可以不使用returnxxx來(lái)設(shè)置xxx為函數(shù)返回值荧关。
如果不使用return語(yǔ)句的話(huà)护盈,則函數(shù)里最后一句代碼的執(zhí)行結(jié)果被設(shè)置成返回值。比如
//下面這個(gè)函數(shù)的返回值是字符串"getSomething return value"
def getSomething(){
"getSomething return value" //如果這是最后一行代碼羞酗,則返回類(lèi)型為String
1000//如果這是最后一行代碼,則返回類(lèi)型為Integer
}
Groovy對(duì)字符串支持相當(dāng)強(qiáng)大紊服,充分吸收了一些腳本語(yǔ)言的優(yōu)點(diǎn):
1 單引號(hào)''中的內(nèi)容嚴(yán)格對(duì)應(yīng)Java中的String檀轨,不對(duì)$符號(hào)進(jìn)行轉(zhuǎn)義
def singleQuote='I am $ dolloar' //輸出就是I am $ dolloar
2 雙引號(hào)""的內(nèi)容則和腳本語(yǔ)言的處理有點(diǎn)像,如果字符中有$號(hào)的話(huà)欺嗤,則它會(huì)$表達(dá)式先求值参萄。
def doubleQuoteWithoutDollar = "I am one dollar" //輸出 I am one dollar
def x = 1
def doubleQuoteWithDollar = "I am $x dolloar" //輸出I am 1 dolloar
3 三個(gè)引號(hào)'''xxx'''中的字符串支持隨意換行 比如
def multieLines = ''' begin
line 1
line 2
end '''
最后,除了每行代碼不用加分號(hào)外煎饼,Groovy中函數(shù)調(diào)用的時(shí)候還可以不加括號(hào)讹挎。比如:
println("test") ---> println"test"
list類(lèi)
變量定義:List變量由[]定義,比如
def aList = [5,'string',true] //List由[]定義吆玖,其元素可以是任何對(duì)象
變量存韧怖!:可以直接通過(guò)索引存取,而且不用擔(dān)心索引越界沾乘。如果索引超過(guò)當(dāng)前鏈表長(zhǎng)度怜奖,List會(huì)自動(dòng)
往該索引添加元素
assert aList[1] == 'string'
assert aList[5] == null //第6個(gè)元素為空
aList[100] = 100 //設(shè)置第101個(gè)元素的值為10
assert aList[100] == 100
那么,aList到現(xiàn)在為止有多少個(gè)元素呢翅阵?
println aList.size ===>結(jié)果是101
list操作:
def list = [1,2,3,4,5]
list[1] //Result: 2
list[-2] //Result: 4
list[1..3] //Result: [2, 3, 4]
list[1..<3] //Result: [2, 3]
list + [6,7] //Result: [1, 2, 3, 4, 5, 6, 7]
list - [4,5,6] //Result: [1, 2, 3]
list << 6 //Result: [1, 2, 3, 4, 5, 6]
list << [6,7] //Result: [1, 2, 3, 4, 5, 6, [6, 7]]
list方法:
[2,5].add(7) //Result: true; list = [2, 5, 7]
[2,5].add(1,9) //list = [2, 7, 5]
[2,5].add([7,9]) //Result: [2, 5, [7, 9]]
[2, 5, [7, 9]].flatten() //Result: [2, 5, 7, 9]歪玲;克隆并解開(kāi)下層list
[2,5].get(1) //Result: 5
[2,5].size() //Result: 2
[2,5].isEmpty() //Result: false
[2,5].getAt(1) //Result: 5
[2,5,7].getAt(1..2) //Result: [5, 7]
[2,5,7].getAt(-1) //Result: 7;get()不支持負(fù)數(shù)參數(shù)掷匠,getAt()支持
[2,5,7].getAt([1,2]) //Result: [5, 7]
[2,5,7].intersect([5,9,2]) //Result: [5, 2]滥崩;交集
[2,5,7].pop() //Result: 7
[2,5,7].plus([3,6]) //Result: [2, 5, 7, 3, 6]
[2,5,7,2].minus(2) //Result: [5, 7]
[2,5,7].remove(1) //Result: 5; list = [2, 7]
[2,7,5].reverse() //Result: [5, 7, 2]
[2,7,5].sort() //Result: [2, 5, 7]
map類(lèi)
// 變量定義:Map變量由[:]定義,比如
def aMap=[:]
def aMap = ['key1':'value1','key2':true]
// Map由[:]定義讹语,注意其中的冒號(hào)钙皮。冒號(hào)左邊是key,右邊是Value募强。
// key必須是字符串株灸,value可以是任何對(duì)象。另外擎值,key可以用''或""包起來(lái)慌烧,也可以不用引號(hào)包起來(lái)。比如
def aNewMap = [key1:"value",key2:true]
// 其中的key1和key2默認(rèn)被處理成字符串"key1"和"key2"
// 不過(guò)Key要是不使用引號(hào)包起來(lái)的話(huà)鸠儿,也會(huì)帶來(lái)一定混淆屹蚊,比如
def key1="wowo"
def aConfusedMap=[key1:"who am i?"]
// aConfuseMap中的key1到底是"key1"還是變量key1的值“wowo”厕氨?顯然,答案是字符串"key1"汹粤。
// 如果要是"wowo"的話(huà)命斧,則aConfusedMap的定義必須設(shè)置成:
def aConfusedMap=[(key1):"who am i?"]
// Map中元素的存取更加方便,它支持多種方法:
println aMap.keyName // 這種表達(dá)方法好像key就是aMap的一個(gè)成員變量一樣
println aMap['keyName'] // 這種表達(dá)方法更傳統(tǒng)一點(diǎn)
aMap.anotherkey = "i am map" // 為map添加新元素
map.put('height', '175') //Result: ["name":"Bruce", "age":27, "weight":"60kg",
map操作:
def map = [3:56, 'name':'Bruce']
def a = 'name'
map.name //Result: "Bruce"
map['name'] //Result: "Bruce"
map[a] //Result: "Bruce"
map[3] //Result: 56
以下訪(fǎng)問(wèn)是錯(cuò)誤的嘱兼,會(huì)拋出異常
map[name]
map.3
map方法:
def map = ['name':'Bruce', 'age':27]
map.containsKey('name') //Result: true
map.get('name') //Result: "Bruce"
map.get('weight', '60kg') //Result: "60kg"国葬;會(huì)把key:value加進(jìn)去
map.getAt('age') //Result: 27
map.keySet() //Result: [name, age, weight]
map.put('height', '175') //Result: ["name":"Bruce", "age":27, "weight":"60kg", "height":"175"]
map.values().asList() //Result: ["Bruce", 27, "60kg", "175"]
map.size() //Result: 4
map遍歷
1、使用each方法
Students.each {
def student ->
println "the key is ${student.key} and the value is ${student.value}"
}
這種方式是根據(jù)Map集合中的Entry(鍵值對(duì))進(jìn)行遍歷的芹壕,還可以根據(jù)key與value進(jìn)行遍歷汇四,需要注意的是,key與value參數(shù)的順序不能顛倒踢涌,否則會(huì)造成數(shù)據(jù)的錯(cuò)亂
// 直接遍歷key, value而不再是遍歷entry
Students.each { key, value ->
println "the key is ${key} and , the value is ${value}"
}
2通孽、eachWithIndex方法
這個(gè)是帶索引的遍歷
// 帶索引的each遍歷
Students.eachWithIndex { def student, int index -> // 二者的順序不能顛倒
println "the index is ${index} , the key is ${student.key} , and the value is ${student.value}"
}
這個(gè)方法同樣頁(yè)可以使用key與value的方式進(jìn)行帶索引的map集合遍歷,使用eachWithIndex方法睁壁,但是同樣index必須為最后一個(gè)參數(shù)背苦,否則會(huì)造成數(shù)據(jù)錯(cuò)亂
Students.eachWithIndex { def key, def value, int index -> // 三者的順序不能顛倒
println "the index is ${index} , the key is ${key} , and the value is ${value}"
}
students.find{key,value ->
}
range類(lèi)
def aRange = 1..5 // <==Range類(lèi)型的變量 由begin值+兩個(gè)點(diǎn)+end值表示左邊這個(gè)aRange包含1,2,3,4,5這5個(gè)值
//如果不想包含最后一個(gè)元素,則
def aRangeWithoutEnd = 1..<5 // 包含1,2,3,4這4個(gè)元素
循環(huán)
def list = [1,2,3,4,5]
for (int i in list){
println i
}
while (n<5){
n+=1
println n
}
for (int i=0;i<5;i++){
println i
}
for(int i in 1..5) {
println(i);
}
def employee = ["Ken" : 21, "John" : 25, "Sally" : 22]
for(emp in employee) {
println(emp);
}
#Ken = 21
#John = 25
#Sally = 22
數(shù)據(jù)類(lèi)型轉(zhuǎn)換
int類(lèi)型--------->String類(lèi)型
方式一:
int num = 100;
String s = "" + num;
方式二:
int num = 100;
String s = String.valueOf(num);
//String類(lèi)下valueOf可將任何類(lèi)型轉(zhuǎn)換成String類(lèi)型
方式三:
int num=100潘明;
Integer in = new Integer(num);
String s= in.toString();
方式四:
int num=100行剂;
String s = Integer.toString(num);
String類(lèi)型--------->int類(lèi)型
方式一:
String s = "100";
Integer in= new Integer(s);
//Integer類(lèi)下將Integer轉(zhuǎn)換成功int的方法
int num = in.intValue();
方式二:
String s=“100”;
int num = Integer.parseInt(s);
json對(duì)象處理
對(duì)象轉(zhuǎn)Json
List轉(zhuǎn)為Json和簡(jiǎn)單钉疫,只需要使用groovy.json包下的JsonOutput類(lèi)即可
import groovy.json.JsonBuilder
imprt groovy.json.JsonOutput
def list = [new Person(name: 'YangHang', age: 25)
, new Person(name: 'YangKunZe', age: 24)]
// 對(duì)象轉(zhuǎn)成Json 兩種方法
def json = JsonOutput.toJson(list)
def json = new JsonBuilder(list)
Json轉(zhuǎn)對(duì)象
同理硼讽,我們需要使用groovy.json包下的JsonSlurper類(lèi)即可
// Json轉(zhuǎn)成對(duì)象
JsonSlurper jsonS = new JsonSlurper()
def l = jsonS.parseText(json) #json指json對(duì)象
讀寫(xiě)文件
// 創(chuàng)建文件對(duì)象
def file = new File('./data.txt')
// 循環(huán)遍歷文件中的每一行
file.eachLine {line ->
println line
}
// 獲取文件中的所有內(nèi)容,返回string類(lèi)型
println file.getText()
// 獲取文件中的所有內(nèi)容牲阁,返回arraylist類(lèi)型
println file.readLines()
// 讀取文件部分內(nèi)容固阁,閉包的方式不需要處理流的關(guān)閉
def reader = file.withReader {reader ->
char[] buffer = new char[1024]
reader.read(buffer)
return buffer
}
println reader
// copy 文件
def copy(String sourcePath, String targetPath) {
// 創(chuàng)建目標(biāo)文件
def targetFile = new File(targetPath)
if (!targetFile.exists()) {
targetFile.createNewFile()
}
// 開(kāi)始 copy
new File(sourcePath).withReader {reader ->
def lines = reader.readLines()
targetFile.withWriter {writer ->
lines.each {line ->
writer.append(line).append("\r\n")
}
}
}
return true
}
println copy('./data.txt', './dataCopy.txt')
// 寫(xiě)入的文件路徑
def filePath1 = "data1.txt"
File file2 = new File(filePath1)
// 寫(xiě)入文件,兩種方式
file2.write("This is line1")
file2 << "\nThis is line2"
// 追加寫(xiě)入文件
file2.append("\nThis is line3")
println file2.text
原文鏈接:https://blog.csdn.net/qq_36929361/article/details/104242748
原文鏈接:https://blog.csdn.net/qq_38056514/article/details/127218578