Gradle學習之三Groovy高階語法

C安君發表於2020-10-16


一、概述

在這裡插入圖片描述

二、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方法

def file = new File('path')
def out = file.newObjectOutputStream()
...
out.close()

相關文章