groovy的IO操作--真是丧心病狂

//groovy用it表InputStream
def targetFile=new File("build.gradle")
def buffer=new byte[1024]
def hasRead
targetFile.withInputStream{ 
    while((hasRead=it.read(buffer))!=-1)
    println(new String(buffer,0,hasRead))

}

task linereadfile <<{
    //it为每一行 读行循环
    def targetFile=new File('build.gradle')
    targetFile.eachLine{
    println it
    }
}
//理解
/*eachLine内部...
def eachLine(Closure closure){
    循环{
    it='一行数据'
    closure(it)//闭包对象调用方法closure.call(实参)
    }
}
*/


task copyfile <<{
//srcFile-->targetFile复制文件
def srcFile = new File("build.gradle")  
def targetFile = new File("haswrite.txt")  
targetFile.withOutputStream{  
    def os=it//输出流
    srcFile.withInputStream{ 
    def ins=it//输入流
      os << ins//利用OutputStream的<<操作符重载,完成从inputstream到OutputStream  
       //的输出  
   } 
   }
   }

task readfile <<{
//一次性读完以byte[]形式返回
def targetFile=new File("build.gradle")
println new String(targetFile.getBytes(),"utf-8")//  <==文件内容一次性读出,返回类型为byte[]  
}

利用Groovy的GPath 解析xml文件资源..
import groovy.util.slurpersupport.GPathResult
//第一步,创建XmlSlurper类  
def xparser = new XmlSlurper()  
def targetFile = new File("test.xml")  
//轰轰的GPath出场  
GPathResult gpathResult =xparser.parse(targetFile)     
//开始玩test.xml。现在我要访问id=4的book元素。  
//下面这种搞法,gpathResult代表根元素response。通过e1.e2.e3这种  
//格式就能访问到各级子元素....  
def book4 = gpathResult.value.books.book[3]  
//得到book4的author元素  
def author = book4.author  
//再来获取元素的属性和textvalue  
println author.text()
println author.@'id'
//assert author.text() == ' Manuel De Cervantes '  
//获取属性更直观  
//author.@id == '4' 或者 author['@id'] == '4'  
//属性一般是字符串,可通过toInteger转换成整数  
//author.@id.toInteger() == 4  
//好了。GPath就说到这。再看个例子。我在使用Gradle的时候有个需求,就是获取AndroidManifest.xml版本号(versionName)。有了GPath,一行代码搞定,请看:  
def androidManifest = xparser.parse("AndroidManifest.xml")  
//获取application的android:label属性,匹配不到则无任何异常输出.
println androidManifest.application[0].@'android:label'
//或者  
println androidManifest.@'android:versionName'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秋葵好吃吗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值