Gradle学习之三Groovy高级语法

系列文章目

Gradle学习之一入门介绍
Gradle学习之二Groovy核心语法
Gradle学习之三Groovy高级语法
Gradle学习之四Gradle生命周期
Gradle学习之五Project详解
Gradle学习之六Task详解
Gradle学习之七其他重要模块


一、概述

在这里插入图片描述

二、json操作详解

def list = [
        new Person(name:'zhangsan',age: 18),
        new Person(name:'lisi',age: 18),
        new Person(name:'wangwu',age: 18),
        new Person(name:'zhaoliu',age: 18),
]

//序列化
def json = JsonOutput.toJson(list)
println(json)
def prettyJson = JsonOutput.prettyPrint(json)
println(prettyJson)



//案例:进行网络请求,并进行数据的反序列化
def respone = getNetworkData('http://api.qingyunke.com/api.php?key=free&appid=0&msg=%E5%8C%97%E4%BA%AC%E5%A4%A9%E6%B0%94')
println respone

//根据Url请求网络
def getNetworkData(String url){
    
    
    def connection = new URL(url).openConnection()
    connection.setRequestMethod('GET')
    connection.connect()
    def res = connection.content.text
    //反序列化
    def jsonSlurper = new JsonSlurper()
    return jsonSlurper.parseText(res)
}

对XML处理
在这里插入图片描述
在这里插入图片描述


def xmlData = '''
    <bookstore>
        <book category="COOKING">
            <title lang="en">Everyday Italian</title>
            <author>Giada De Laurentiis</author>
            <year>2005</year>
            <price>30.00</price>
        </book>
        
        <book category="COOKING">
            <title lang="en">James Harden</title>
            <author>L J</author>
            <year>2005</year>
            <price>30.00</price>
        </book>
        
        <book category="CHILDREN">
            <title lang="en">Harry Potter</title>
            <author>J K. Rowling</author>
            <year>2005</year>
            <price>29.99</price>
        </book>
        <book category="WEB">
            <title lang="en">Learning XML</title>
            <author>L J</author>
            <year>2003</year>
            <price>39.95</price>
        </book>
    </bookstore>
'''

//序列化
def xmlSlurper = new XmlSlurper()
def bookstore = xmlSlurper.parseText(xmlData)

//打印属性
println bookstore.book[0].title.text()
println bookstore.book[0].title.@lang
//深度优先遍历
def titles = bookstore.depthFirst().findAll {
    
     book->
    book.author.text()== 'L J'
}
println titles

def list = []
bookstore.book.each {
    
    book-> if(book.author.text() == 'L J'){
    
    
    list.add(book.title.text())
} }
println list

//广度遍历查找COOKING类型图书
def result = bookstore.children()
        .findAll {
    
     book-> book.@category == 'COOKING'}
        .collect( book-> book.title.text())
println result

接下来看一下自定义XML字符串

//创建XML字符串,使用
def stringWriter = new StringWriter()
def mb = new MarkupBuilder(stringWriter)

mb.bookstore(){
    
    
	//显式指明属性
    book(category:'COOKING'){
    
    
        title(lang:'en','Everyday Italian')
        //直接设置标签对应的value
        author('Giada De Laurentiis')
        year(2005)
        price(30.00)
    }
    book(category:'COOKING'){
    
    
        title(lang:'en','James Harden')
        author('L J')
        year(2010)
        price(30.00)
    }
    book(category:'CHILDREN'){
    
    
        title(lang:'en','Harry Potter')
        author('J K. Rowling')
        year(2005)
        price(29.99)
    }

    book(category:'WEB'){
    
    
        title(lang:'en','Learning XML')
        author('L J')
        year(2003)
        price(1.99)
    }
}


println stringWriter

运行结果:

<bookstore>
  <book category='COOKING'>
    <title lang='en'>Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>
  <book category='COOKING'>
    <title lang='en'>James Harden</title>
    <author>L J</author>
    <year>2010</year>
    <price>30.00</price>
  </book>
  <book category='CHILDREN'>
    <title lang='en'>Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category='WEB'>
    <title lang='en'>Learning XML</title>
    <author>L J</author>
    <year>2003</year>
    <price>1.99</price>
  </book>
</bookstore>

最后看一下,将Bean对象转换为xml:

/**
*声明Bean类
*/
class Bookstore {
    
    
    def books = [
            new Book(category:'COOKING',lang: 'en',titleName: 'Everyday Italian',author:'Giada De Laurentiis',year: 2005,price: 200),
            new Book(category:'COOKING',lang: 'ch',titleName: 'James Harden',author:'L J',year: 2005,price: 200),
            new Book(category:'CHILDREN',lang: 'en',titleName: 'Harry Potter',author:'JK rowling',year: 2005,price: 200),
            new Book(category:'WEB',lang: 'en',titleName: 'Learning XML',author:'L J',year: 2005,price: 200),
    ]
}
class Book{
    
    
    String category
    String lang
    String titleName
    String author
    Number year
    Number price
}

//实例化Bean对象
def bookstore = new Bookstore()
def stringWriter = new StringWriter()
def mb = new MarkupBuilder(stringWriter)
mb.bookstore{
    
    
	//使用循环+闭包的形式创建xml结点
    bookstore.books.each {
    
    book->
        Book(category:book.category){
    
    
            title(lang:book.lang,book.titleName)
            author(book.author)
            year(book.year)
            price("$book.price \$")
        }
    }
}

println stringWriter

三、文件操作详解

在这里插入图片描述
在这里插入图片描述

def file = new File('path')
//遍历文件的每一行
file.eachLine{
    
     line ->
	println line
}
//获取文件的内容
def text = file.getText()
//获取文件内容 每一行(返回一个数组)
def result = file.readLines()
//读取100个字符
def reader = file.withReader{
    
     reader->
	charp[] buff = new char[100]
	reader.read(buff)
	return buff
}

//文件拷贝
def copy(String sourcePath,String destPath){
    
    
	try{
    
    
		//确保目标文件存在
		def destFile = new File(destPath)
		if(!destFile.exists()){
    
    
			destFile.createNewFile()
		}
		
		//拷贝操作
		new File(sourcePath).withReader{
    
     reader->
			def lines = reader.readLines()
			destFile.withWriter{
    
     writer ->
				lines.each{
    
    line ->
					writer.append(line+"\r\n")
				}
			}
		}
	}catch(Exception e){
    
    
		e.printStackTrace()
	}
}

对象文件读写

def saveObject(Object object,String path){
    
    
	try{
    
    
		//确保目标文件存在
		def destFile = new File(destPath)
		if(!destFile.exists()){
    
    
			destFile.createNewFile()
		}
		
		//写对象
		destFile.withObjectOutputStream{
    
     out->
			out.writeObject(object)
		}
	}catch(Exception e){
    
    
		e.printStackTrace()
	}
}

def readObject(String path){
    
    
	def result = null
	try{
    
    
		//确保目标文件存在
		def file = new File(path)
		if(file == null || !file.exists()){
    
    
			return null
		}
		
		//写对象
		file.withObjectInputStream{
    
     in->
			result =  in.readObject()
		}
	}catch(Exception e){
    
    
		e.printStackTrace()
	}
	return result;
}

注意:如果IO流对象是new的,则需要显式的调用close方法

扫描二维码关注公众号,回复: 11947289 查看本文章
def file = new File('path')
def out = file.newObjectOutputStream()
...
out.close()

猜你喜欢

转载自blog.csdn.net/dirksmaller/article/details/109097591