Gradle自动化项目构建技术-3.Groovy高级用法

栏目: Groovy · 发布时间: 6年前

内容简介:运行结果:还提供了一种可以格式化打印的方法:运行结果:
Gradle自动化项目构建技术-3.Groovy高级用法

3.1 Json操作详解

将实体对象转化为json

def list = [new Person(name: 'Jhon',age: 25),
            new Person(name: 'Major',age: 26)]
def json = JsonOutput.toJson(list)
println json

运行结果:

[{"age":25,"name":"Jhon"},{"age":26,"name":"Major"}]

还提供了一种可以格式化打印的方法:

println JsonOutput.prettyPrint(json)

运行结果:

[
    {
        "age": 25,
        "name": "Jhon"
    },
    {
        "age": 26,
        "name": "Major"
    }
]

从网络请求的数据转为实体对象

def getNetworkData(String url){
    def connection = new URL(url).openConnection()
    connection.setRequestMethod('GET')
    connection.connect()
    def response = connection.content.text

    //将json转换为实体对象
    def jsonSluper = new JsonSlurper()
    return jsonSluper.parseText(response)
}

def response = getNetworkData("")
println response.data.head.name

3.2 xml处理详解

先定义一段xml:

final String xml = '''
    <response version-api="2.0">
        <value>
            <books id="1" classification="android">
                <book available="20" id="1">
                    <title>疯狂Android讲义</title>
                    <author id="1">李刚</author>
                </book>
                <book available="14" id="2">
                   <title>第一行代码</title>
                   <author id="2">郭林</author>
               </book>
               <book available="13" id="3">
                   <title>Android开发艺术探索</title>
                   <author id="3">任玉刚</author>
               </book>
               <book available="5" id="4">
                   <title>Android源码设计模式</title>
                   <author id="4">何红辉</author>
               </book>
           </books>
           <books id="2" classification="web">
               <book available="10" id="1">
                   <title>Vue从入门到精通</title>
                   <author id="4">李刚</author>
               </book>
           </books>
       </value>
    </response>
'''

最简单的解析xml

// 开始解析此xml数据
def xmlSluper = new XmlSlurper()
def resonse = xmlSluper.parseText(xml)

println resonse.value.books[0].book[0].title.text()
println resonse.value.books[0].book[0].author.text()
println resonse.value.books[1].book[0].@available

运行结果:

疯狂Android讲义
李刚
10

从书节点进行遍历

//书结点进行遍历
def list = []
resonse.value.books.each{ books ->
    books.book.each{ book ->
        def author = book.author.text()
        if (author.equals('李刚')){
            list.add(book.title.text())
        }
    }
}
println list.toListString()

运行结果:

[疯狂Android讲义, Vue从入门到精通]

深度遍历xml数据

//深度遍历xml数据
def titles = resonse.depthFirst().findAll {book ->
    return book.author.text() == '李刚'?true: false
}

println titles.toListString()

运行结果:

[疯狂Android讲义李刚, Vue从入门到精通李刚]

广度遍历xml数据

//广度遍历xml数据
def name = resonse.value.books.children().findAll{ node ->
    node.name() == 'book' && node.@id == 2
}.collect{node ->
    return node.title.text()
}
println name

运行结果:

[第一行代码]

生成xml格式数据

生成xml格式数据
<langs type='current' count='3' mainstream='true'>
  <language flavor='static' version='1.5'>Java</language>
  <language flavor='dynamic' version='1.3'>Groovy</language>
  <language flavor='dynamic' version='1.6'>JavaScript</language>
</langs>
  • 使用MarkupBuilder生成xml

    def sw = new StringWriter()
    // 用来生成xml数据的核心类
    def xmlBuilder = new MarkupBuilder(sw)
    xmlBuilder.langs(type: 'current',count:'3',mainstream:'true'){
        //第一个language节点
        language(flavor:'static',version:'1.5'){
            age('16')
        }
        language(flavor:'dynamic',version:'1.6.0','Groovy')
        language(flavor:'dynamic',version:'1.9','JavaScript')
    }
    println sw
    
  • 使用实体类生成xml

    def langs = new Langs()
    xmlBuilder.langs(type: langs.type,count:langs.count,mainstream: langs.mainstream){
        langs.languages.each {lang ->
            language(flavor:lang.flavor,version:lang.version,lang.value)
        }
    }
    println sw
    
    //对应xml中的langs结点
    class Langs{
        String type = 'current'
        int count = 3
        boolean  mainstream = true
    
        def languages = [
                new Language(flavor: 'static',
                        version: '1.5', value: 'Java'),
                new Language(flavor: 'dynamic',
                        version: '1.3', value: 'Groovy'),
                new Language(flavor: 'dynamic',
                        version: '1.6', value: 'JavaScript')
        ]
    }
    
    //对应xml中的languang结点
    class Language{
        String flavor
        String version
        String value
    }
    

    运行结果:

    <langs type='current' count='3' mainstream='true'>
      <language flavor='static' version='1.5'>
        <age>16</age>
      </language>
      <language flavor='dynamic' version='1.6.0'>Groovy</language>
      <language flavor='dynamic' version='1.9'>JavaScript</language>
    </langs>
    

3.3 file操作详解

定义一个file

def file = new File('../../HelloGroovy.iml')

file的读取方式

  • 方式1

    file.eachLine {line ->
        println line
    }
    

    运行结果:

    <?xml version="1.0" encoding="UTF-8"?>
    <module type="JAVA_MODULE" version="4">
      <component name="NewModuleRootManager" inherit-compiler-output="true">
        <exclude-output />
        <content url="file://$MODULE_DIR$">
          <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
        </content>
        <orderEntry type="inheritedJdk" />
        <orderEntry type="sourceFolder" forTests="false" />
        <orderEntry type="library" name="groovy-2.5.2" level="application" />
      </component>
    </module>
    
  • 方式2

    def text = file.getText()
    println text
    

    运行结果:

    <?xml version="1.0" encoding="UTF-8"?>
    <module type="JAVA_MODULE" version="4">
      <component name="NewModuleRootManager" inherit-compiler-output="true">
        <exclude-output />
        <content url="file://$MODULE_DIR$">
          <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
        </content>
        <orderEntry type="inheritedJdk" />
        <orderEntry type="sourceFolder" forTests="false" />
        <orderEntry type="library" name="groovy-2.5.2" level="application" />
      </component>
    </module>
    
  • 方式3

    def result = file.readLines()
    println result.toListString()
    

    运行结果:

    [<?xml version="1.0" encoding="UTF-8"?>, <module type="JAVA_MODULE" version="4">,   <component name="NewModuleRootManager" inherit-compiler-output="true">,     <exclude-output />,     <content url="file://$MODULE_DIR$">,       <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />,     </content>,     <orderEntry type="inheritedJdk" />,     <orderEntry type="sourceFolder" forTests="false" />,     <orderEntry type="library" name="groovy-2.5.2" level="application" />,   </component>, </module>]
    
  • 方式4

    // 读取文件部分内容
    def reader = file.withReader {reader ->
        char[] buffer = new char[100]
        reader.read(buffer)
        return buffer
    }
    println reader
    

    运行结果:

    <?xml version="1.0" encoding="UTF-8"?>
    <module type="JAVA_MODULE" version="4">
      <component name="Ne
    

拷贝文件

// 拷贝文件
def copy(String sourcePath,String destationPath){
    try {
        def desFile = new File(destationPath)
        if (!desFile.exists()){
            desFile.createNewFile()
        }

        new File(sourcePath).withReader {reader ->
            def lines = reader.readLines()
            desFile.withWriter { writer ->
                lines.each {line ->
                    writer.append(line + "\r\n")
                }
            }
        }
        return true
    }catch (Exception e){
        e.printStackTrace()
    }
    return false
}

def copyResult = copy('../../HelloGroovy.iml',
        '../../HelloGroovy2.iml')
println copyResult

运行之后,控制台返回true,然后再目录中生成了HelloGroovy2.iml文件

Gradle自动化项目构建技术-3.Groovy高级用法

将对象序列化保存成文件

// 将对象序列化保存成文件

def saveObject(Object object,String path){
    try {
        def desFile = new File(path)
        if (!desFile.exists()){
            desFile.createNewFile()
        }
        desFile.withObjectOutputStream {out ->
            out.writeObject(object)
        }
        return true
    }catch (Exception e){
        e.printStackTrace()
    }
    return false

}

def person = new Person(name: 'shijiacheng', age: 25)
saveObject(person, '../../person.bin')

读取文件内容转化为序列化对象

// 读取文件内容转化为序列化对象

def readObject(String path){
    def obj = null
    try {
        def file = new File(path)
        if (file == null || !file.exists())
            return null

        file.withObjectInputStream {input ->
            obj = input.readObject()
        }
    }catch (Exception e){
        e.printStackTrace()
    }

    return obj
}
def readReuslt = (Person) readObject('../../person.bin')
println "the name is ${readReuslt.name} and the age is ${readReuslt.age}"

运行结果:

the name is shijiacheng and the age is 25

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

移动Web前端高效开发实战

移动Web前端高效开发实战

iKcamp / 电子工业出版社 / 2017-9 / 89.00

移动互联网的兴起和快速普及,给前端开发人员带来了前所未有的新机遇。移动Web前端技术作为整个技术链条中重要的一环,却乱象丛生。《移动Web前端高效开发实战:HTML 5 + CSS 3 + JavaScript + Webpack + React Native + Vue.js + Node.js》是一本梳理移动前端和Native客户端技术体系的入门实战书。 《移动Web前端高效开发实战:HTML......一起来看看 《移动Web前端高效开发实战》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

html转js在线工具
html转js在线工具

html转js在线工具