Groovy: Get keyboard input from console

有時候在寫一些 command line 的工具時,會需要等待鍵盤輸入,再取值繼續處理,在 Groovy 可以這樣寫:

    System.in.withReader {
        print "Please input you name:"
        String name = it.readLine()
        print "Please input you age:"
        String agr = it.readLine()
        println "Your name is $name and the age is $age."
    }

withReader(closure) 是 Groovy 提供的一個 method, 傳入一個 closure. withReader 會將 reader 當作參數傳入 closure, 因此在 closure 內 it 指的就是 reader, 所以可以用 it.readLine() 讀取鍵盤輸入。

2 thoughts on “Groovy: Get keyboard input from console

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s