Groovy是一种基于Java平台的面向对象语言。 Groovy 1.0于2007年1月2日发布,其中Groovy 2.4是当前的主要版本。 Groovy经过Apache License v 2.0发布。html
Groovy中有如下特色:java
Groovy的官方网站是http://www.groovy-lang.org/web
有多种方式来得到的Groovy环境设置。正则表达式
下载和安装 -进入该连接www.groovy-lang.org/download.html得到Windows安装程序部分。shell
启动Groovy安装程序,而后请执行如下完成安装步骤。express
第1步 -选择语言安装程序。编程
第2步 -点击下一步按钮。数组
第3步 -点击“我赞成”按钮。less
第4步 -接受默认组件,而后单击下一步按钮。dom
第5步 -选择适当的目标文件夹,而后单击下一步按钮。
第6步 -点击安装按钮开始安装。
第7步 -一旦安装完成后,单击下一步按钮开始配置。
第8步 -选择默认选项,并单击下一步按钮。
第9步 -接受默认的文件关联,而后单击下一步按钮。
第10步 -单击Finish按钮完成安装。
一旦上述步骤以后,你就能够开始使用Groovy shell,有助于测试咱们的Groovy,而不须要为Groovy提供一个完整的集成开发环境。能够经过在命令提示符下命令groovysh来完成。
'org.codehaus.groovy:groovy:2.4.5'
<groupId>org.codehaus.groovy</groupId> <artifactId>groovy</artifactId> <version>2.4.5</version>
Groovy 基本语法
为了了解Groovy的基本语法,让咱们先看看一个简单的Hello World程序。
建立Hello World程序,你只要输入如下几行简单的代码就可实现 -
class Example { static void main(String[] args) { // Using a simple println statement to print output to the console println('Hello World'); } }
当咱们运行上面的程序,咱们会获得如下结果 -
Hello World
import语句能够用来导入,能够在你的代码可使用其余库的功能。这是经过使用在 Import 关键字完成。
下面的示例演示了如何使用MarkupBuilder的类,它多是最经常使用的建立HTML或XML标记的类之一。
import groovy.xml.MarkupBuilder def xml = new MarkupBuilder()
默认状况下,Groovy在代码中包括如下库,所以您不须要显式导入它们。
import java.lang.* import java.util.* import java.io.* import java.net.* import groovy.lang.* import groovy.util.* import java.math.BigInteger import java.math.BigDecimal
令牌能够是一个关键字,一个标识符,常量,字符串文字或符号。
println(“Hello World”);
在上面的代码行中,有两个令牌,首先是关键词的println而接下来就是字符串的“Hello World”。
在您的代码中使用注释。Groovy的注释能够是单行或多行。
单行注释使用//在该行的任何位置来识别。一个例子以下所示 -
class Example { static void main(String[] args) { // Using a simple println statement to print output to the console println('Hello World'); } }
多行注释标识与在开始/ *和* /识别多行注释的末尾。
class Example { static void main(String[] args) { /* This program is the first program This program shows how to display hello world */ println('Hello World'); } }
就像Java编程语言,它须要具备分号在Groovy定义多个语句之间进行区分。
class Example { static void main(String[] args) { // One can see the use of a semi-colon after each statement def x = 5; println('Hello World'); } }
上述例子示出了分号使用了不一样行的代码语句之间进行区分。
标识符被用来定义变量,函数或其余用户定义的变量。标识符以字母开头,美圆或下划线。他们不能以数字开头。如下是有效标识符的一些例子
def employeename def student1 def student_name
其中,DEF是在Groovy用来定义标识符的关键字。
下面是一个如何在咱们的Hello World程序中使用标识符的代码示例。
class Example { static void main(String[] args) { // One can see the use of a semi-colon after each statement def x = 5; println('Hello World'); } }
在上述的例子中,变量x被用做标识符。
as | assert | break | case |
catch | class | const | continue |
def | default | do | else |
enum | extends | false | Finally |
for | goto | if | implements |
import | in | instanceof | interface |
new | pull | package | return |
super | switch | this | throw |
throws | trait | true | try |
while |
空白是在编程语言如Java和Groovy用来形容空格,制表符,换行符和注释术语。空格分隔从另外一个声明的一部分,使编译器,其中一个元素标识的声明。
例如,在下面的代码示例,存在关键字def和变量x之间的空白。这是为了让编译器知道DEF是须要被使用,而且是x应该是须要被定义的变量名的关键字。
def x = 5;
文字是在groovy中表示固定值的符号。Groovy语言有符号整数,浮点数,字符和字符串。下面是一些在Groovy编程语言文字的例子 -
12 1.45 ‘a’ “aa”
在任何编程语言中,须要使用各类变量来存储各类类型的信息。变量只是保留值的存储位置,这意味着,当你建立一个变量,你保留在内存中的一些空间来存储与变量相关的值。
您可能喜欢存储各类数据类型的信息,如字符串,字符,宽字符,整数,浮点数,布尔值等。基于变量的数据类型,操做系统分配内存并决定什么能够存储在保留的存储器中。
Groovy提供多种内置数据类型。如下是在Groovy中定义的数据类型的列表 -
byte -这是用来表示字节值。例如2。
short -这是用来表示一个短整型。例如10。
int -这是用来表示整数。例如1234。
long -这是用来表示一个长整型。例如10000090。
float -这是用来表示32位浮点数。例如12.34。
double -这是用来表示64位浮点数,这些数字是有时可能须要的更长的十进制数表示。例如12.3456565。
char -这定义了单个字符文字。例如“A”。
Boolean -这表示一个布尔值,能够是true或false。
String -这些是以字符串的形式表示的文本。例如,“Hello World”的。
下表显示了数字和小数点文字中的最大容许值。
byte | -128到127 |
short | -32,768到32,767 |
int | 2,147,483,648 到,147,483,647 |
long | -9,223,372,036,854,775,808到+9,223,372,036,854,775,807 |
float | 1.40129846432481707e-45到3.40282346638528860e + 38 |
double | 4.94065645841246544e-324d 到1.79769313486231570e + 308d |
类型除了基本类型,还容许如下对象类型(有时称为包装器类型)-
此外,如下类可用于支持高精度计算 -
名称 | 描述 | 例如 |
---|---|---|
java.math.BigInteger | 不可变的任意精度的有符号整数数字 | 30克 |
java.math.BigDecimal | 不可变的任意精度的有符号十进制数 | 3.5克 |
如下代码示例说明如何使用不一样的内置数据类型 -
class Example { static void main(String[] args) { //Example of a int datatype int x = 5; //Example of a long datatype long y = 100L; //Example of a floating point datatype float a = 10.56f; //Example of a double datatype double b = 10.5e40; //Example of a BigInteger datatype BigInteger bi = 30g; //Example of a BigDecimal datatype BigDecimal bd = 3.5g; println(x); println(y); println(a); println(b); println(bi); println(bd); } }
当咱们运行上面的程序,咱们会获得如下结果 -
5 100 10.56 1.05E41 30 3.5
Groovy中的变量能够经过两种方式定义 - 使用数据类型的本地语法,或者使用def关键字。对于变量定义,必须明确提供类型名称或在替换中使用“def”。这是Groovy解析器须要的。
Groovy中有如下基本类型的变量,如上一章所述 -
byte - 这用于表示字节值。例如2。
short - 用于表示一个短数。例如10。
int - 这用于表示整数。 例如1234。
long - 这用于表示一个长数。例如10000090。
float - 用于表示32位浮点数。例如12.34。
double - 这用于表示64位浮点数。例如12.3456565。
char - 这定义了单个字符文字。例如'a'。
Boolean - 这表示一个布尔值,能够是true或false。
String - 这是以字符串形式表示的文本。 例如“Hello World”。
Groovy还容许其余类型的变量,如数组,结构和类,咱们将在后续章节中看到。
变量声明告诉编译器为变量建立存储的位置和大小。
下面是一个变量声明的例子 -
class Example { static void main(String[] args) { // x is defined as a variable String x = "Hello"; // The value of the variable is printed to the console println(x); } }
当咱们运行上面的程序,咱们会获得如下结果 -
Hello
变量的名称能够由字母,数字和下划线字符组成。 它必须以字母或下划线开头。 大写和小写字母是不一样的,由于Groovy,就像Java是一种区分大小写的编程语言。
class Example { static void main(String[] args) { // Defining a variable in lowercase int x = 5; // Defining a variable in uppercase int X = 6; // Defining a variable with the underscore in it's name def _Name = "Joe"; println(x); println(X); println(_Name); } }
当咱们运行上面的程序,咱们会获得如下结果 -
5 6 Joe
咱们能够看到x和X是两个不一样的变量,由于区分大小写,在第三种状况下,咱们能够看到_Name如下划线开头。
您可使用println函数打印变量的当前值。下面的示例显示了如何实现这一点。
class Example { static void main(String[] args) { //Initializing 2 variables int x = 5; int X = 6; //Printing the value of the variables to the console println("The value of x is " + x + "The value of X is " + X); } }
当咱们运行上面的程序,咱们会获得如下结果 -
The value of x is 5 The value of X is 6
运算符是一个符号,通知编译器执行特定的数学或逻辑操做。
Groovy中有如下类型的运算符 -
Groovy语言支持正常的算术运算符任何语言。如下是在Groovy中可用的算术运算符 -
运算符 | 描述 | 例子 |
+ | 两个操做数的加法 | 1 + 2 将获得 3 |
- | 第一第二操做数相减 |
2 - 1 将获得 1 |
* | 两个操做数的乘法 | 2 * 2 将获得4 |
/ | 两个操做数的除法 | 3/2 将获得 1.5 |
% | 取模运算 | 3%2 将获得 1 |
++ | 自增运算,在自身值的基础上加1 | INT X = 5; X ++; X 将获得 6 |
-- | 自减运算,在自身值的基础上减1 |
INT X = 5; X - -; X 将获得 4 |
运算符 | 描述 | 例子 |
---|---|---|
== | 测试两个对象之间是否相等 | 2 == 2 将获得 true |
!= | 测试两个对象之间是否不等 | 3 != 2 将获得 true |
< | 检查是否左边的对象是小于右边的对象。 | 2 < 3 将获得 true |
<= | 检查是否向左对象是小于或等于右边的对象 | 2 <= 3 将获得 true |
> | 检查是否左边的对象比右边的对象大。 | 3 > 2 将获得 true |
>= | 检查是否向左对象大于或等于右边的对象。 | 3>= 2 将获得 true |
逻辑运算符用于计算布尔表达式。如下是在Groovy中提供的逻辑运算符 -
运算符 | 描述 | 例子 |
---|---|---|
&& | 这是逻辑“与”运算 | true && true 获得 true |
|| | 这是逻辑“或”运算 | true || true 获得 true |
! | 这是逻辑“非”运算 | !true 获得 false |
Groovy中提供了四个位运算符。如下是在Groovy中可用的位运算符 -
运算符 | 描述 |
---|---|
& | 这是位“与”运算 |
| | 这是按位“或”运算 |
^ | 这是按位“异或”或异或运算符 |
〜 | 这是按位反运算符 |
这里是显示这些运算符的真值表。
p | q | p&Q | p | q | p ^ Q |
---|---|---|---|---|
0 | 0 | 0 | 0 | 0 |
0 | 1 | 0 | 1 | 1 |
1 | 1 | 1 | 1 | 0 |
1 | 0 | 0 | 1 | 1 |
Groovy语言也提供了赋值操做符。如下是在Groovy提供的赋值运算符 -
运算符 | 描述 | 例子 |
---|---|---|
+= | A += B 等价于 A = A+B | DEF A = 5 A += 3 输出将是8 |
-= | A -= B 等价于 A = A-B | DEF A = 5 A -= 3 输出将是2 |
*= | A *= B 等价于 A= A*B | DEF A = 5 A *= 3 输出将是15 |
/= | A /= B 等价于 A = A/B | DEF A = 6 A /= 3 输出将是2 |
(%)= | A (%)= B 等价于 A = A % B | DEF A = 5 A %= 3 输出将是2 |
Groovy支持范围的概念,并在..符号的帮助下提供范围运算符的符号。下面给出了范围运算符的一个简单示例。
def range = 0..5
这只是定义了一个简单的整数范围,存储到一个局部变量称为范围内的下限为0和上限为5。
如下代码段显示了如何使用各类运算符。
class Example { static void main(String[] args) { def range = 5..10; println(range); println(range.get(2)); } }
当咱们运行上面的程序,咱们会获得如下结果 -
从println语句中,能够看到显示在range语句中定义的整个数字范围。
get语句用于从定义的范围中获取一个对象,它将索引值做为参数。
[5, 6, 7, 8, 9, 10] 7
下表按优先级顺序列出了全部groovy运算符
运算符 | 名称 |
---|---|
++ - + - | 预增/减,一元加,一元减 |
* / % | 乘法,除法,取模 |
+ - | 加法,减法 |
==!= <=> | 等于,不等于,比较 |
& | 二进制/位运算符与 |
^ | 二进制/位异或 |
| | 二进制/按位或 |
&& | 逻辑和 |
|| | 逻辑或 |
= ** = * = / =%= + = - = << = >> = >>> = = ^ = | = | 各类赋值运算符 |
到目前为止,咱们已经看到已经按顺序方式一个接一个执行的语句。此外,在Groovy中提供了语句来改变程序逻辑中的控制流。而后将它们分类为咱们将详细看到的控制语句的流程。
序号 | 语句和描述 |
---|---|
1 | while语句 while语句首先经过计算条件表达式(布尔值)来执行,若是结果为真,则执行while循环中的语句。 |
2 | for语句 for语句用于遍历一组值。 |
3 | for-in语句 for-in语句用于遍历一组值。 |
序号 | 语句和描述 |
---|---|
1 | break语句 break语句用于改变循环和switch语句内的控制流。 |
2 | continue语句 continue语句补充了break语句。它的使用仅限于while和for循环。 |
第一个决策语句是 if 语句。这种说法的通常形式是 -
if(condition) { statement #1 statement #2 ... }
这个语句的通常工做是首先在 if 语句中评估一个条件。若是条件为真,它而后执行语句。下图显示了 if 语句的流程。
下面是一个if / else语句的例子 -
class Example { static void main(String[] args) { // Initializing a local variable int a = 2 //Check for the boolean condition if (a<100) { //If the condition is true print the following statement println("The value is less than 100"); } } }
在上面的例子中,咱们首先将一个变量初始化为值2.而后咱们评估变量的值,而后决定是否应该执行 println 语句。上面的代码的输出将是 -
The value is less than 100
咱们将看到的下一个决策语句是 if / else 语句。这种说法的通常形式是 -
if(condition) { statement #1 statement #2 ... } else{ statement #3 statement #4 }
这个语句的通常工做是首先在 if 语句中评估一个条件。若是条件为真,则其后执行语句,并在else条件以前中止并退出循环。若是条件为假,则执行else语句块中的语句,而后退出循环。下图显示了 if 语句的流程。
下面是一个if / else语句的例子 -
class Example { static void main(String[] args) { // Initializing a local variable int a = 2 //Check for the boolean condition if (a<100) { //If the condition is true print the following statement println("The value is less than 100"); } else { //If the condition is false print the following statement println("The value is greater than 100"); } } }
在上面的例子中,咱们首先将一个变量初始化为值2.而后咱们评估变量的值,而后决定应该执行哪一个 println 语句。上面的代码的输出将是
The value is less than 100.
有时须要有多个if语句嵌入在彼此内部。
这种说法的通常形式是 -
if(condition) { statement #1 statement #2 ... } else if(condition) { statement #3 statement #4 } else { statement #5 statement #6 }
如下是嵌套if / else语句的示例 -
class Example { static void main(String[] args) { // Initializing a local variable int a = 12 //Check for the boolean condition if (a>100) { //If the condition is true print the following statement println("The value is less than 100"); } else // Check if the value of a is greater than 5 if (a>5) { //If the condition is true print the following statement println("The value is greater than 5 and greater than 100"); } else { //If the condition is false print the following statement println("The value of a is less than 5"); } } }
在上面的例子中,咱们首先将一个变量初始化为值12.在第一个 if 语句中,咱们看到 a 的值是否大于100。若是没有,那么咱们进入第二个for循环,看看 a 的值是否大于5或小于5.上面的代码的输出将是 -
The value is greater than 5 and greater than 100
有时,嵌套的if-else语句是如此常见,而且常用,以便设计一个更容易的语句,称为 switch 语句。
switch(expression) { case expression #1: statement #1 ... case expression #2: statement #2 ... case expression #N: statement #N ... default: statement #Default ... }
本声明的通常工做以下 -
要评估的表达式放在switch语句中。
将有多个case表达式被定义以基于表达式的计算来决定应该执行哪一组语句。
在结尾处的语句的每一个案例段中添加一个 break 语句。这是为了确保在执行相关语句集时当即退出循环。
还有一个默认case 语句,若是没有任何前面的状况表达式求值为true,则执行。
下图显示了 switch-case 语句的流程。
如下是switch语句的示例 -
class Example { static void main(String[] args) { //initializing a local variable int a = 2 //Evaluating the expression value switch(a) { //There is case statement defined for 4 cases // Each case statement section has a break condition to exit the loop case 1: println("The value of a is One"); break; case 2: println("The value of a is Two"); break; case 3: println("The value of a is Three"); break; case 4: println("The value of a is Four"); break; default: println("The value is unknown"); break; } } }
在上面的例子中,咱们首先将一个变量初始化为值2.而后咱们有一个switch语句,它计算变量a的值。 基于变量的值,它将执行语句的相关案例集。上面的代码的输出将是 -
The value of a is Two
它也能够有一个嵌套的 switch 语句。语句的通常形式以下所示 -
switch(expression) { case expression #1: statement #1 ... case expression #2: statement #2 ... case expression #N: statement #N ... default: statement #Default ... }
下面是嵌套switch语句的一个示例 -
class Example { static void main(String[] args) { //Initializing 2 variables i and j int i = 0; int j = 1; // First evaluating the value of variable i switch(i) { case 0: // Next evaluating the value of variable j switch(j) { case 0: println("i is 0, j is 0"); break; case 1: println("i is 0, j is 1"); break; // The default condition for the inner switch statement default: println("nested default case!!"); } break; // The default condition for the outer switch statement default: println("No matching case found!!"); } } }
在上面的例子中,咱们首先将a的变量初始化为a的值为2.而后咱们有一个 switch 语句,它计算变量 a 的值。 基于变量的值,它将执行语句的相关案例集。上面的代码的输出将是 -
i is 0, j is 1
Groovy中的方法是使用返回类型或使用def关键字定义的。方法能够接收任意数量的参数。定义参数时,没必要显式定义类型。能够添加修饰符,如public,private和protected。默认状况下,若是未提供可见性修饰符,则该方法为public。
最简单的方法是没有参数的方法,以下所示:
def methodName() { //Method code }
下面是一个简单方法的例子
class Example { static def DisplayName() { println("This is how methods work in groovy"); println("This is an example of a simple method"); } static void main(String[] args) { DisplayName(); } }
在上面的例子中,DisplayName是一个简单的方法,它由两个println语句组成,用于向控制台输出一些文本。在咱们的静态main方法中,咱们只是调用DisplayName方法。上述方法的输出将是 -
This is how methods work in groovy This is an example of a simple method
若是一个方法的行为由一个或多个参数的值肯定,则它一般是有用的。咱们可使用方法参数将值传递给被调用的方法。请注意,参数名称必须彼此不一样。
使用参数的最简单的方法类型,以下所示 −
def methodName(parameter1, parameter2, parameter3) { // Method code goes here }
如下是使用参数的简单方法的示例
class Example { static void sum(int a,int b) { int c = a+b; println(c); } static void main(String[] args) { sum(10,5); } }
在这个例子中,咱们建立一个带有2个参数a和b的sum方法。两个参数都是int类型。而后咱们从咱们的main方法中调用sum方法,并将值传递给变量a和b。
而后咱们从咱们的main方法中调用sum方法,并将值传递给变量a和b。Groovy中还有一个规定来指定方法中的参数的默认值。 若是没有值传递给参数的方法,则使用缺省值。 若是使用非默认和默认参数,则必须注意,默认参数应在参数列表的末尾定义。
如下是使用参数的简单方法的示例 -
def someMethod(parameter1, parameter2 = 0, parameter3 = 0) { // Method code goes here }
让咱们看看咱们以前看到的添加两个数字的相同示例,并建立一个具备一个默认和另外一个非默认参数的方法 -
class Example { static void sum(int a,int b = 5) { int c = a+b; println(c); } static void main(String[] args) { sum(6); } }在这个例子中,咱们建立一个具备两个参数a和b的sum方法。两个参数都是int类型。此示例和上一个示例的区别在于,在这种状况下,咱们将b的默认值指定为5。
class Example { static void sum(int a,int b = 5) { int c = a+b; println(c); } static void main(String[] args) { sum(6,6); } }咱们也能够经过传递2个值来调用sum方法,在上面的例子中,咱们传递2个值6.第二个值6实际上将替换分配给参数b的默认值。
class Example { static void sum(int a,int b = 5) { int c = a+b; return c; } static void main(String[] args) { println(sum(6)); } }在咱们上面的例子中,注意此次咱们为咱们的方法sum指定一个类型为int的返回类型。 在方法中,咱们使用return语句将sum值发送到调用主程序。 因为方法的值如今可用于main方法,所以咱们使用println函数在控制台中显示该值。 在前面的例子中,咱们将咱们的方法定义为静态方法,这意味着咱们能够直接从类中访问这些方法。方法的下一个示例是实例方法,其中经过建立类的对象来访问方法。咱们将在后面的章节中看到类,如今咱们将演示如何使用方法。
方法一般在Groovy中的类中实现,就像Java语言同样。类只是一个蓝图或模板,用于建立定义其属性和行为的不一样对象。类对象显示由其类定义的属性和行为。所以,经过在类中建立方法来定义行为。
咱们将在后面的章节中更详细地看到类,下面是类中方法实现的例子。class Example { int x; public int getX() { return x; } public void setX(int pX) { x = pX; } static void main(String[] args) { Example ex = new Example(); ex.setX(100); println(ex.getX()); } }在咱们上面的例子中,此次咱们没有为类方法指定静态属性。在咱们的main函数中,咱们实际上建立了一个Example类的实例,而后调用'ex'对象的方法。
Groovy提供的设施就像java同样具备本地和全局参数。在下面的示例中,lx是一个局部参数,它只具备getX()函数内的做用域,x是一个全局属性,能够在整个Example类中访问。若是咱们尝试访问getX()函数以外的变量lx,咱们将获得一个错误。
class Example { static int x = 100; public static int getX() { int lx = 200; println(lx); return x; } static void main(String[] args) { println getX() } }
当咱们运行上面的程序,咱们会获得如下结果。
200 100
就像在Java中同样,groovy可使用this关键字访问它的实例成员。如下示例显示了当咱们使用语句this.x时,它引用其实例并相应地设置x的值。
class Example { int x = 100; public int getX() { this.x = 200; return x; } static void main(String[] args) { Example ex = new Example(); println(ex.getX()); } }
当咱们运行上面的程序,咱们将获得200的结果打印在控制台上。
Groovy在使用I / O时提供了许多辅助方法,Groovy提供了更简单的类来为文件提供如下功能。
除此以外,您始终可使用下面列出的用于文件I / O操做的标准Java类。
如下示例将输出Groovy中的文本文件的全部行。方法eachLine内置在Groovy中的File类中,目的是确保文本文件的每一行都被读取。
import java.io.File class Example { static void main(String[] args) { new File("E:/Example.txt").eachLine { line -> println "line : $line"; } } }File类用于实例化以文件名做为参数的新对象。 而后它接受eachLine的函数,将它放到一个line的变量并相应地打印它。
line : Example1 line : Example2
若是要将文件的整个内容做为字符串获取,可使用文件类的text属性。如下示例显示如何完成此操做。
class Example { static void main(String[] args) { File file = new File("E:/Example.txt") println file.text } }
若是该文件包含如下行,它们将被打印出来。
line : Example1 line : Example2
若是你想写入文件,你须要使用做家类输出文本到一个文件中。下面的例子说明了如何能够作到这一点。
import java.io.File class Example { static void main(String[] args) { new File('E:/','Example.txt').withWriter('utf-8') { writer -> writer.writeLine 'Hello World' } } }
若是你打开文件example.txt文件,您将看到文本中打印了“Hello World”这个词。
若是要获取文件的大小,可使用文件类的length属性来获取,如下示例显示如何完成此操做。
class Example { static void main(String[] args) { File file = new File("E:/Example.txt") println "The file ${file.absolutePath} has ${file.length()} bytes" } }
上面的代码将显示文件的大小(以字节为单位)。
若是要查看路径是文件仍是目录,可使用File类的isFile和isDirectory选项。如下示例显示如何完成此操做。
class Example { static void main(String[] args) { def file = new File('E:/') println "File? ${file.isFile()}" println "Directory? ${file.isDirectory()}" } }
上面的代码将显示如下输出 -
File? false Directory? True
若是要建立一个新目录,可使用File类的mkdir函数。如下示例显示如何完成此操做。
class Example { static void main(String[] args) { def file = new File('E:/Directory') file.mkdir() } }
若是目录E:\ Directory不存在,将建立它。
若是要删除文件,可使用File类的delete功能。如下示例显示如何完成此操做。
class Example { static void main(String[] args) { def file = new File('E:/Example.txt') file.delete() } }
若是存在该文件将被删除。
Groovy还提供将内容从一个文件复制到另外一个文件的功能。如下示例显示如何完成此操做。
class Example { static void main(String[] args) { def src = new File("E:/Example.txt") def dst = new File("E:/Example1.txt") dst << src.text } }
将建立文件Example1.txt,并将文件Example.txt的全部内容复制到此文件。
Groovy还提供了列出驱动器中的驱动器和文件的功能。
如下示例显示如何使用File类的listRoots函数显示机器上的驱动器。
class Example { static void main(String[] args) { def rootFiles = new File("test").listRoots() rootFiles.each { file -> println file.absolutePath } } }
根据机器上可用的驱动器,输出可能会有所不一样。在标准机器上的输出将相似于下面的一个 -
C:\ D:\
如下示例显示如何使用File类的eachFile函数列出特定目录中的文件。
class Example { static void main(String[] args) { new File("E:/Temp").eachFile() { file->println file.getAbsolutePath() } } }
输出将显示目录E:\ Temp中的全部文件
若是要递归显示目录及其子目录中的全部文件,则可使用File类的eachFileRecurse函数。如下示例显示如何完成此操做。
class Example { static void main(String[] args) { new File("E:/temp").eachFileRecurse() { file -> println file.getAbsolutePath() } } }
输出将显示目录E:\ Temp中的全部文件及其子目录(若是存在)。
Groovy是一个“可选”类型的语言,当理解语言的基本原理时,这种区别是一个重要的语言。与Java相比,Java是一种“强”类型的语言,由此编译器知道每一个变量的全部类型,而且能够在编译时理解和尊重合同。这意味着方法调用可以在编译时肯定。
当在Groovy中编写代码时,开发人员能够灵活地提供类型或不是类型。这能够提供一些简单的实现,而且当正确利用时,能够以强大和动态的方式为您的应用程序提供服务。
在Groovy中,可选的键入是经过'def'关键字完成的。下面是一个使用def方法的例子 -
class Example { static void main(String[] args) { // Example of an Integer using def def a = 100; println(a); // Example of an float using def def b = 100.10; println(b); // Example of an Double using def def c = 100.101; println(c); // Example of an String using def def d = "HelloWorld"; println(d); } }
从上面的程序,咱们能够看到,咱们没有声明单个变量为Integer,float,double或string,即便它们包含这些类型的值。
当咱们运行上面的程序,咱们将获得如下结果 -
100 100.10 100.101 HelloWorld
可选的打字在开发期间能够是一个强大的实用程序,可是当代码变得太大和复杂时,可能致使在后期开发阶段的可维护性问题。
要了解如何使用Groovy中的可选输入,而不让代码库陷入没法维护的混乱,最好在应用程序中采用“鸭式输入”的理念。
若是咱们使用鸭式重写上面的代码,它将看起来像下面给出的。变量名称的名称比它们表明的类型更多,这使得代码更容易理解。
class Example { static void main(String[] args) { // Example of an Integer using def def aint = 100; println(aint); // Example of an float using def def bfloat = 100.10; println(bfloat); // Example of an Double using def def cDouble = 100.101; println(cDouble); // Example of an String using def def dString = "HelloWorld"; println(dString); } }
在Groovy中,数字实际上表示为对象,它们都是类Integer的一个实例。要使对象作某事,咱们须要调用在其类中声明的一个方法。
Groovy支持整数和浮点数。
Groovy中的数字示例以下所示 -
Integer x = 5; Float y = 1.25;
其中x是整数类型,y是浮点数。
groovy中的数字被定义为对象的缘由一般是由于存在对数字执行操做的要求。在原始类型上提供类的概念被称为包装类。
默认状况下,Groovy中提供了如下包装程序类。
包装类的对象包含或包装其各自的基本数据类型。将原始数据类型转换为对象的过程称为装箱,这由编译器负责。将对象转换回其对应的基本类型的过程称为取消装箱。
如下是装箱和拆箱的例子 -
class Example { static void main(String[] args) { Integer x = 5,y = 10,z = 0; // The the values of 5,10 and 0 are boxed into Integer types // The values of x and y are unboxed and the addition is performed z = x+y; println(z); } }
上述程序的输出将为5.在上述示例中,5,10和0的值相应地首先嵌入到整数变量x,y和z中。上述程序的输出将是5。而后,当执行x和y的添加时,值从其整数类型取消装箱。
因为Groovy中的Numbers表示为类,如下是可用的方法列表。
序号 | 方法和描述 |
---|---|
1 | xxxValue() 此方法接受Number做为参数,并基于调用的方法返回基本类型。 |
2 | compareTo() compareTo方法是使用比较一个数字与另外一个数字。若是要比较数字的值,这是有用的。 |
3 | equals() 该方法肯定调用方法的Number对象是否等于做为参数传递的对象。 |
4 | valueOf() valueOf方法返回保存所传递的参数的值的相关Number对象。 |
5 | toString() 该方法用于获取表示Number对象的值的String对象。 |
6 | parseInt() 此方法用于获取某个String的原始数据类型。 parseXxx()是一个静态方法,能够有一个参数或两个参数。 |
7 | abs() 该方法给出了参数的绝对值。参数能够是int,float,long,double,short,byte。 |
8 | ceil() 方法ceil给出大于或等于参数的最小整数。 |
9 | floor() 方法floor给出小于或等于参数的最大整数。 |
10 | rint() 方法rint返回值最接近参数的整数。 |
11 | round() 方法round返回最接近的long或int,由方法返回类型给出。 |
12 | min() 该方法给出两个参数中较小的一个。参数能够是int,float,long,double。 |
13 | max() 该方法给出了两个参数的最大值。参数能够是int,float,long,double。 |
14 | exp() 该方法返回天然对数e的底数为参数的幂。 |
15 | log() 该方法返回参数的天然对数。 |
16 | pow() 该方法返回第一个参数的值增长到第二个参数的幂。 |
17 | sqrt() 该方法返回参数的平方根。 |
18 | sin() 该方法返回指定double值的正弦值。 |
19 | cos() 该方法返回指定double值的余弦值。 |
20 | tan() 该方法返回指定double值的正切值。 |
21 | asin() 该方法返回指定double值的反正弦值。 |
22 | acos() 该方法返回指定double值的反余弦值。 |
23 | atan() 该方法返回指定double值的反正切。 |
24 | atan2() 该方法将直角坐标(x,y)转换为极坐标(r,theta),并返回theta。 |
25 | parseInt() 该方法将参数值转换为度。 |
26 | radian() 该方法将参数值转换为弧度。 |
27 | random() 该方法用于生成介于0.0和1.0之间的随机数。范围是:0.0 = <Math.random <1.0。经过使用算术能够实现不一样的范围。 |
此方法接受Number做为参数,并基于调用的方法返回基本类型。 如下是可用的方法列表 -
byte byteValue() short shortValue() int intValue() long longValue() float floatValue() double doubleValue()
参数 - 无需参数。
返回值 - 返回值是根据调用的值函数返回的原始类型。
如下是方法值的用法示例。
class Example { static void main(String[] args) { Integer x = 5; // Converting the number to double primitive type println(x.doubleValue()); // Converting the number to byte primitive type println(x.byteValue()); // Converting the number to float primitive type println(x.floatValue()); // Converting the number to long primitive type println(x.longValue()); // Converting the number to short primitive type println(x.shortValue()); // Converting the number to int primitive type println(x.intValue()); } }
当咱们运行上面的程序,咱们将获得如下结果 -
5.0 5 5.0 5 5 5
compareTo方法是使用比较一个数字与另外一个数字。若是要比较数字的值,这是有用的。
public int compareTo( NumberSubClass referenceName )
referenceName - 这能够是字节,双精度,整数,浮点型,长整型或短整型。
下面是一个使用这个方法的例子 -
class Example { static void main(String[] args) { Integer x = 5; //Comparison against a Integer of lower value System.out.println(x.compareTo(3)); //Comparison against a Integer of equal value System.out.println(x.compareTo(5)); //Comparison against a Integer of higher value System.out.println(x.compareTo(8)); } }
当咱们运行上面的程序,咱们将获得如下结果 -
1 0 -1
该方法肯定调用方法的Number对象是否等于做为参数传递的对象。
public boolean equals(Object o)
o - 任何对象。
若是参数不为空,而且是同一类型且具备相同数值的对象,则方法返回True。
下面是一个使用这个方法的例子 -
class Example { static void main(String[] args) { Integer x = 5; Integer y = 10; Integer z = 5; //Comparison against an Integer of different value System.out.println(x.equals(y)); //Comparison against an Integer of same value System.out.println(x.equals(z)); } }
当咱们运行上面的程序,咱们将获得如下结果 -
false true
--------------------------------------------------------------------------