/**
* 參考資料
* Groovy之旅系列
* Groovy之invokeMethod
*/
//讀取文件內容1
number = 0
new File("src/FileExample.groovy").eachLine({
line ->
number ++
println("$number:$line")
})
//讀取文件內容2
println new File("src/FileExample.groovy").getText()
//創建目錄
import static java.io.File.separator as sep
new File(System.properties.'user.home'+sep+'.11groovy'+sep+'lib').mkdirs()
//寫入文件
def outFile = new File('mydata.txt')
def printWriter = outFile.newPrintWriter()
printWriter.println("面朝大海, 春暖花開!")
printWriter.flush()
printWriter.close()
/**
* 讀取xml文件
<?xml version="1.0" ?>
<customers>
<corporate>
<customer name="Bill Gates" company="Microsoft" />
<customer name="Steve Jobs" company="Apple" />
<customer name="Jonathan Schwartz" company="Sun" />
</corporate>
<consumer>
<customer name="John Doe" />
<customer name="Jane Doe" />
</consumer>
</customers>
*/
def customers = new XmlSlurper().parse(new File("src/customer.xml"))
for(customer in customers.corporate.customer)
{
println "${customer.@name} works for ${customer.@company}";
}
//寫入xml文件,使用大括號{}將生成標簽,使用在括號()用來定義屬性。
import groovy.xml.MarkupBuilder
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
xml.records() {
car(name:'polo', maker:'Shanghai Volkswagen', year:2006) {
price('&26000')
comment('a good car for you')
}
car(name:'camry', make:'Toyota', year:2005) {
price('$19000')
comment('The low petrol consumption cars ')
}
}
println writer.toString()