用Groovy讀取本地文件的代碼

下面這些包默認已經被導入了,不需要使用import再次顯式導入:

  • java.io.*
  • java.lang.*
  • java.math.BigDecimal
  • java.math.BigInteger
  • java.net.*
  • java.util.*
  • groovy.lang.*
  • groovy.util.*

Groovy的運行時方法調用抉擇

運行時,Groovy根據參數類型決定具體哪一個方法被執行。而Java恰恰相反,被調用的方法根據參數類型,在編譯期間就已經定下來了。

In Groovy, the methods which will be invoked are chosen at runtime. This is called runtime dispatch or multi-methods. It means that the method will be chosen based on the types of the arguments at runtime. In Java, this is the opposite: methods are chosen at compile time, based on the declared types.

下列代碼的打印結果是1:

int method(String arg) {
	return 1;
}
int method(Object arg) {
	return 2;
}
Object o = "Object";
int result = method(o);

println result

在Groovy裏,成對的大括號是聲明閉包用的,因此定義數組的語法改用中括號:

int[] array = [1, 2, 3]

Groovy裏的閉包,it爲默認參數:

Closures may have 1…N arguments, which may be statically typed or untyped. The first parameter is available via an implicit untyped argument named it if no explicit arguments are named. If the caller does not specify any arguments, the first parameter (and, by extension, it) will be null.

That means that a Groovy Closure will always have at least one argument, called it (if not specified otherwise) and it will be null if not given as a parameter.

看個用Groovy讀取本地文件內容的代碼,和Java比起來短小精悍:

我的文件內容:

輸出:

這種方法也行:

完整代碼:

new File('c:\\temp\\1.txt').eachLine('UTF-8') {
	println "new line->" + it
 }

 
 new File('c:\\temp\\1.txt').withReader('UTF-8') { reader ->
	 reader.eachLine {
		 println "Another line:" + it
	 }
  }

要獲取更多Jerry的原創文章,請關注公衆號"汪子熙":

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章