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
          數(shù)據(jù)加載中……

          groovy操作文件及xml

          /**
           * 參考資料
           * Groovy之旅系列
           * Groovy之invokeMethod
           */

          //讀取文件內(nèi)容1
          number = 0
          new File("src/FileExample.groovy").eachLine({
              line ->
              number ++
              println("$number:$line")
          })

          //讀取文件內(nèi)容2
          println new File("src/FileExample.groovy").getText()

          //創(chuàng)建目錄
          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

          主站蜘蛛池模板: 门头沟区| 贺州市| 太和县| 华坪县| 延津县| 泰兴市| 嘉义县| 清远市| 同仁县| 宿迁市| 苗栗县| 温州市| 裕民县| 井冈山市| 阳西县| 石林| 锡林浩特市| 南雄市| 沁源县| 平原县| 胶南市| 呈贡县| 永平县| 清镇市| 唐河县| 鄂伦春自治旗| 舒城县| 宁夏| 吴忠市| 德昌县| 宝清县| 青海省| 云霄县| 巴彦县| 湘乡市| 章丘市| 开江县| 朔州市| 余姚市| 金坛市| 中江县|