本文主要是介绍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'
这篇关于groovy的IO操作--真是丧心病狂的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!