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 大石頭 閱讀(1681) 評論(0)  編輯  收藏 所屬分類: Groovy

          主站蜘蛛池模板: 贺兰县| 泸定县| 温宿县| 阳泉市| 德惠市| 东城区| 辰溪县| 曲麻莱县| 哈尔滨市| 特克斯县| 广灵县| 武隆县| 东港市| 鹿泉市| 临朐县| 瑞昌市| 亚东县| 新闻| 娱乐| 盐边县| 湘阴县| 西华县| 马鞍山市| 开鲁县| 香港| 鹿泉市| 东源县| 吉林市| 汝城县| 桦川县| 措勤县| 石家庄市| 施秉县| 彭水| 温州市| 偃师市| 台江县| 屏东县| 鹿泉市| 晋城| 临汾市|