groovy基本类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package primary

class TypeDemo {

static void main(args) {

int x = 5;

long y = 100L;

float a = 10.56f;

double b = 10.5e40;

BigInteger bi = 30g;

BigDecimal bd = 3.5g;

println(x);
println(y);
println(a);
println(b);
println(bi);
println(bd);

println("The value of x is " + x + "The value of y is " + y);
}


}

groovy特殊运算符

1.范围运算符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package primary

class OperatorDemo {

static void main(String[] args) {

//定义离散变量组,从0到10
def range = 0..10 ;

println(range);
println(range.get(2));
}
}

输出结果

1
2
0..10
2

运算符优先级

++--+- 预增/减(自增/减),一元加,一元减
* / 乘法,除法,取模
+- 加法,减法(二元)
==!=<=> 等于,不等于,比较运算符
二进制/位运算符与
^ 二进制/位异或
` `
逻辑非
&& 逻辑与
`
=+=-=*=/=%=**= 各种赋值运算符

for-in语句

特殊循环,类似于java for 循环增强

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package primary

class forDemo {

static void main(String[] args) {

def range = 0..10

for (i in range) {
println(i)
}

def users = ["z":21,"s":11]

for(user in users){
println(user.key+":"+user.value)
}

}
}

方法

函数列表默认值

1
2
3
4
5
6
7
8
9
10
11
12
13
package primary;

class FunctionDemo {

static void main(String[] args) {
println (sum(1,1))
}

static int sum(int a, int b = 0) {
a+b
}
}

IO操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package io

class IOUtils {

static void main(String[] args) {

new File("E://data//test").eachLine {
line -> println "line:$line"
}

//读取文件到字符串
File file = new File("E://data//test")
println file.text

//写入文件
new File("E://data//test").withWriter {
writer -> writer.writeLine 'Hello World!'
}

println file.text

//获取文件大小
println "The file ${file.absolutePath} has ${file.length()} bytes"

//判断文件是否是目录
println "File? ${file.isFile()}"
println "Directory? ${file.isDirectory()}"

//创建文件目录
def directory = new File('E:/groovy/Directory')
directory.mkdirs()

def newFile = new File(directory, "newFile")
newFile.createNewFile()

//复制文件
def copyFile = new File(directory, "copyFile")
copyFile << newFile

println("copyFile is create:${copyFile.exists()}")

copyFile.delete()
println("copyFile is delete?${copyFile.exists()}")

//显示根目录
def rootFiles = new File("test").listRoots()
rootFiles.each {println it.absolutePath}

rootFiles.each {
//遍历目录及子集
it.eachFileRecurse(){recurse->
println(recurse.absolutePath)
}

}
}
}