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
--------------------------------------------------------------------------