Learn Groovy

Quick Start

1. download groovy-binary-1.7.3.zip, and unzip into, for example, d:\groovy-binary-1.7.3
2. add d:\groovy-binary-1.7.3\bin into Window PATH
3. Write file of test1.g, the content is "println new Date()"
4. Make sure you have installed JDK, run command groovy test1.g, you will get date string, for example,  "Tue Jul 17 09:59:49 CST 2012"


http://groovy.codehaus.org/
http://groovy.codehaus.org/User+Guide
http://groovy.codehaus.org/groovy-jdk/
http://blog.csdn.net/hivon/article/details/4256296


Java中的equals方法对应Groovy中的== , 而Java中的==(判断是否引用同一对象)对应Groovy中的is方法。


======File Operation

---transfer file character encoding
new FileOutputStream("out.txt").withWriter("UTF-8") { writer ->
    new FileInputStream("in.txt").withReader("ISO-8859-1") { reader ->
        writer << reader
    }
}

def f=new File("c:/data/myiso88591.xml").getText("ISO-8859-1")
new File("c:/data/myutf8.xml").write(f,"utf-8")

def writer=new File("FileWrite.out").newWriter()
writer.writeLine("contents")
writer.close()

file.eachLine ("utf8") { println it}
new File("test").eachFile() { file->  println file.getName()
new File("test").eachDirRecurse() { dir ->  println dir.getPath()} }  

======Collection

---Map
def map = [:]
def map=[name:"Gromit", likes:"cheese", id:1234]
map.each{key, value -> print key}
map.keySet().each{print it}
assert map.get("name") == "Gromit"
map.put("foo", 5)
assert map.size() == 1
map['name'] //Result: "Bruce"
map[a]      //Result: "Bruce"
map[3]      //Result: 56
map.containsKey('name')   //Result: true

---List
assert [1, 3, 5] == ['a', 'few', 'words']*.size()
def words = ['ant', 'buffalo', 'cat', 'dinosaur']
assert words.collect{ it[0] } == ['a', 'b', 'c', 'd']
list + [6,7]   //Result: [1, 2, 3, 4, 5, 6, 7]
list << 6      //Result: [1, 2, 3, 4, 5, 6]
list << [6,7]  //Result: [1, 2, 3, 4, 5, 6, [6, 7]]
[2,5,7].remove(1)          //Result: 5; list = [2, 7]
[2,5].isEmpty()            //Result: false
[2,5].get(1)               //Result: 5
[2,5].size()               //Result: 2
[2,5].add(7)               //Result: true; list = [2, 5, 7]
def a1=(1..10).grep{it<5 && it>3} //[4]
a1=(1..10).collect{it<2} //[true, false, false, false, false, false, false, false, false, false]
a1=(1..10).every{it>2}    //false
a1=(1..10).find{it>2} //3, it is first matched
list.eachWithIndex { elem, i ->println "$i : $elem"}
def list = [2007, 8, 26] list.sort { e1, e2 ->return e1 - e2}
'a1/b2/c3/d4'.tokenize('/') /["a1", "b2", "c3", "d4"]
def list = ['a', 'ab', 'a'] list.count('a')
def list = [1, 2, 3] list.sum() // 6

======String

def str2 = 'hello world it is a groovy world'.split(' ').collect{it[0].toUpperCase()+(it.size()>1?it[1..-1]:'')}.join(' ') //Hello World It Is A Groovy World
propName.substring(1,propName.length())
propName.substring(0,1).toUpperCase()
println str[1..-2] //获取从下标1开始,到倒数第二位的子串
println str[1..2]//下标为1和2处的子串

包含一个最简单正则表达式的表达式是用==~.
"beijing" ==~ /beijing/
check("I love beijing?",/[^/?]+/?/) //必须在?前面加'/'进行转义

locationData = "Liverpool, England: 53° 25? 0? N 3° 0? 0?" --> myRegularExpression = /([a-zA-Z]+), ([a-zA-Z]+): ([0-9]+). ([0-9]+). ([0-9]+). ([A-Z]) ([0-9]+). ([0-9]+). ([0-9]+)./
matcher = ( locationData =~ myRegularExpression )
for(int i = 0;i < matcher[0].size; i ++)   {      println(matcher[0][i])  }
就用到了非俘获组.表示方法就是用?: 加上你要过滤的正则前面.
myMatcher = (it =~ /(.*?)(?:   .+)+ (.*)/) --> "ZDW   love beijing",
matcher = (it =~ /(.*?)(?: .+)+ (.*)/);  --> "Graham James Edward Miller",
m="10.128.12.16" =~ /(/d.*?)/./ --> //星号加个问题,表示非贪婪匹配,输出为 10

======database
import groovy.sql.Sql;
sql = Sql.newInstance("jdbc:jtds:sqlserver://localhost/pubs","sa","","net.sourceforge.jtds.jdbc.Driver");
sql.eachRow("select * from person", {  println it.id + "-- ${it.username} -- ${it.password} -- ${it.age}"});
row = sql.firstRow("select username,password from person");
println "Row: username = ${row.username} and password = ${row.password}";
sql.execute("insert into person (username, password) values (${username}, ${password})")
sql.execute("insert into person values ('admin','admin',99)");
sql.execute("insert into person (username,password) values (? , ?)",[username,password]);
sql.execute("update person set username = 'dddd' where id = ?",[id]);
sql.execute("delete from person where id = ?",[2])

=======多线程
t = new Thread() {println "a"};
t.start();
Thread.start { println "a"};
Thread.startDaemon { println "a"};
new Timer().runAfter(1000) { println "a"}

======swing
import groovy.swing.SwingBuilder
import javax.swing.*
import java.awt.*
def swing = new SwingBuilder()
def swing_count = 0
def sharedPanel = {swing.panel() {label("??Panel")}}
def textlabel
def frame =
    swing.frame(title:'??Panel??', size:[600,600], defaultCloseOperation:JFrame.EXIT_ON_CLOSE, pack:true,show:true)
    {
        boxLayout(axis:BoxLayout.Y_AXIS)
        textlabel = label(text:"???${swing_count}?.",constraints: BorderLayout.NORTH)
        button(text:'???',actionPerformed: {swing_count++; textlabel.text = "???${swing_count}?"; println "clicked"}, constraints:BorderLayout.SOUTH)
        widget(sharedPanel())
        widget(sharedPanel())
   }
frame.pack()
frame.show()



======class
class Person {String name1;String m1(String v1){return v1+v1};def m2(v1){return v1+v1}}
Person.metaClass.introduce << {println "I'm $name1"}
Person.metaClass.constructor << { name, sex ->new Person(name:name, sex:sex)}

======闭包
将代码块作为方法参数进行传递,这种机制就叫做闭包
默认的闭包带一个参数"it",你也能创建闭包用自命名参数.例如方法Map.each()
如果是多个参数的闭包,则在闭包中用 "->" 把参数列表和实现隔开,如:(当然一个参数也可以这么方式定义的)
square = {it * it}
[ 1, 2, 3, 4 ].collect(square) // [ 1, 4, 9, 16 ]
printMapClosure = { key, value -> println key + "=" + value }
[ "yue" : "wu", "lane" : "burks", "sudha" : "saseethiaseeleethialeselan" ].each(printMapClosure)
myMap.keySet().each( { result+= myMap[it] } ) //匿名闭包


====== utils
---   Groovy File and URL MD5
import java.security.MessageDigest
def generateMD5(final file) {
  MessageDigest digest = MessageDigest.getInstance("MD5")
  file.withInputStream(){is->
    byte[] buffer = new byte[8192]
    int read = 0
    while( (read = is.read(buffer)) > 0) {   digest.update(buffer, 0, read);}
  }
  byte[] md5sum = digest.digest()
  BigInteger bigInt = new BigInteger(1, md5sum)
  return bigInt.toString(16)
}

---listAllFiles
import groovy.io.FileType
def list = []
new File(path_to_parent_dir).eachFileRecurse (FileType.FILES) { file ->  list << file}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值