keep moving!

We must not cease from exploration. And the end of all our exploring will be to arrive where we began and to know the place for the first time.
随笔 - 37, 文章 - 2, 评论 - 3, 引用 - 0
数据加载中……

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()

posted on 2008-09-01 12:51 大石头 阅读(1670) 评论(0)  编辑  收藏 所属分类: Groovy


只有注册用户登录后才能发表评论。


网站导航: