groovy操作文件及xml

groovy操作文件及xml

/**
 * 参考资料
 * 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()

你可能感兴趣的:(groovy操作文件及xml)