Hello World on Groovy

3912 ワード

1、雑学
package groovy

class Foo {

	def static openFile(fileName) {
		new FileInputStream(fileName)
	}

	def static foo(str) {
		str?.reverse()
	}

	def static returnWhat() {
		println "returnWhat() executed!"
		this
	}

	public static void main(String[] args) {

		/* 
		 *  , ( )
		 *  
		 */
		println returnWhat().returnWhat().returnWhat()

		/* openFile  */
		try {
			openFile("nonexistentfile" )
		} catch(FileNotFoundException ex) {
			println ex
		}

		/*  ?.  */
		println foo('evil' )
		println foo(null)

		/*  、  */
		List lst = [1, 2, 3]
		lst.each { print "$it " }
		print "
" for(j in 5..9) { print j + " " } print "
" 10.upto 15, { print "$it " } print "
" 3.times { print "--
" } 0.step(10, 2) { print "$it " } /* */ print "
" println "java -version".execute().text /* */ lst<<4 println lst } }

出力:
returnWhat() executed!
returnWhat() executed!
returnWhat() executed!
class groovy.Foo
java.io.FileNotFoundException:nonexistentfile(指定されたファイルが見つかりません.)
live
null
1 2 3
5 6 7 8 9
10 11 12 13 14 15
--
--
--
0 2 4 6 8
[1, 2, 3, 4]
二、オブジェクトとスレッド
package groovy

class Customer {

	Integer id;

	String name;

	Date dob;

	static void main(args) {
		def customer = new Customer(id:1, name:"sunny", dob:new Date())
		println "dob is $customer.dob!"

		assert Byte.MAX_VALUE == 127
		assert Byte.MIN_VALUE == -128

		def i = 0, j = 0
		Thread.start {
			while(true) {
				i++
				if (i%1000 == 0 && i/1000 < 3 ) println 'S'
			}
		}

		while(true) {
			j++
			if (j%1000 == 0 && i/1000 < 3 ) println 'M'
		}
	}
}

出力:
dob is Fri Jul 22 17:54:27 CST 2011!
M
S
M
S
M
三、ファイル操作
package groovy

class FileOperator {

	public static void main(String[] args) {
		def myFile = new File("C:\\ftnstat.stat")
		def printFileLine = {println it}
		myFile.eachLine( printFileLine )
	}
}

出力:
MaxFileUploadParallelNum:0\MaxFileWaitingNum:0\SelectFileTimes:0\UploadFileNum:0\
MaxFileUploadParallelNum:0\MaxFileWaitingNum:0\SelectFileTimes:0\UploadFileNum:0\
MaxFileUploadParallelNum:0\MaxFileWaitingNum:0\SelectFileTimes:0\UploadFileNum:0\
MaxFileUploadParallelNum:0\MaxFileWaitingNum:0\SelectFileTimes:0\UploadFileNum:0\
MaxFileUploadParallelNum:0\MaxFileWaitingNum:0\SelectFileTimes:0\UploadFileNum:0\
四、データベース操作
package groovy

class SqlOperator {

	public static void main(String[] args) {
		def sql = groovy.sql.Sql.newInstance( "jdbc:oracle:thin:@192.168.0.201:1521:oracle9i",
				"gz", "gz", "oracle.jdbc.driver.OracleDriver" )
		def results = []
		sql.eachRow("select * from acl_user", {
			results<<it
			println it.id + " -- ${it.name} "
		})
		println "size = "+results.size()
	}
}

出力:
1227978--甘い鐘
1227982--何毅永
792275--趙清迵
1467305--李沈蔵
934266--マフィン
1596070--徐月平
1792352--呉玉燕
788199--馮暁紅
1920836--梁剣梅
1927141--ウー国威
size = 10