Groovy file operation (the thief is simple, and I don’t want to use java files after use)

After mastering the Json, Xml, and groovy file processing in this chapter, the groovy grammar comes to an end, and then you can step into the long-awaited gradle part.

One, Json processing

The knowledge points of json are generally divided into two partsEntity generates json stringConvert json string to entity. Groovy provides us with API to handle json, which is more powerful than java. In fact, we don’t need to use third-party Kura (Gson, fastGson)

1. Entity generates json string
def list = [new Person(name: "Tom", age: 10),
            new Person(name: "Kate", age: 12)]

def jsonString = JsonOutput.toJson(list) //直接转变为Json
println(jsonString)

println(JsonOutput.prettyPrint(jsonString)) // 格式化输出json
//log:
[{
    
    "age":10,"name":"Tom"},{
    
    "age":12,"name":"Kate"}]
[
    {
    
    
        "age": 10,
        "name": "Tom"
    },
    {
    
    
        "age": 12,
        "name": "Kate"
    }
]

It can be seen that there are two main static methods used during conversion:
1. JsonOutput.toJson (agrs) can directly convert json objects into strings
2. JsonOutput.prettyPrint(string) can directly visualize json strings, which is a convenient one Batch. .

2. Convert json string to entity
// 准备一份json数据
String json = "[{\"age\":10,\"name\":\"Tom\"},{\"age\":12,\"name\":\"Kate\"}]"
def jsonSlurper = new JsonSlurper()

def userList =  jsonSlurper.parseText(json)
println(userList[0].name) //Tom

You can see the main objects and methods used in the conversion:
1. Get the JsonSlurper object
2. The parseXXX() of the object can be

3. Seamlessly connect with various libraries of java

Some people want to say that I still like Gson provided by Google (used more for Android development) or FastJson of Ali (used more for background). Don't worry about groovy, since it seamlessly connects with Java's existing APIs and third-party libraries, it looks like It can be used like java.

(1) Introduction of simple steps on idea

1. Download the java package and put it in the folder on idea (usually we create a libs)
2. Select the java package add as library to use the class

(2) Related networks

In fact, Groovy does not provide a library for network access, we only need to use the java set.

Two, Xml processing

As commonly used as json is to process xml strings or generate xml files.

1. Parse the xml string

In fact, parsing the xml string and parsing the xml file are almost the same, here we take the string as a chestnut

(1) Parse the xml string

1. Obtain the XmlSlurper object (new method)
2. Obtain the node object (the return value of the parseXXX(xmlString) method)
3.Pass node objectGet node value, node attribute value

  • Obtaining the node value: node object.text()
  • Node attribute value access: node object.@attribute
String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
        "<value>\n" +
        "    <books id=\"1\" type=\"android\">\n" +
        "        <book page=\"507\">\n" +
        "            <title>安卓开发艺术探索</title>\n" +
        "            <author>任玉刚</author>\n" +
        "        </book>\n" +
        "        <book page=\"507\">\n" +
        "            <title>第一行代码</title>\n" +
        "            <author>郭霖</author>\n" +
        "        </book>\n" +
        "        <book page=\"100\">\n" +
        "            <title>安卓进阶之光</title>\n" +
        "            <author>刘望舒</author>\n" +
        "        </book>\n" +
        "    </books>\n" +
        "\n" +
        "</value>"
def xmlSlurper = new XmlSlurper()
def value = xmlSlurper.parseText(xmlString) // 1、获得根节点对象

println value.books.book[0].title.text() //2、节点对象调用text()获得节点内的值

println value.books.book[0].@page // 3、对象@属性 直接访问这个属性值

(2)Tradition in the traditional way of closure

1. Traverse: the book with 507 pages.
2. Idea: just traverse the book object

def bklist  = []

value.books.book.each {
    
    

    bk ->
        def pageCount = bk.@page
        if (pageCount == "507") {
    
    
            bklist.add(bk.title.text())
        }
}

println bklist.toListString()
//log:
[安卓开发艺术探索, 第一行代码]

(3) Simpler traversal method provided by Groovy:Deep traversal

println value.depthFirst().findAll(){
    
    
    book-> return book.author.text()=="任玉刚"
}

1. Just call findAll of the depthFirst method of the target node directly, and directly traverse the target node set.
2. The depthFirst method can also use "**" instead

(4) Simpler traversal method provided by Groovy:Breadth traversal

def name= value.books.children().findAll {
    
    
    node -> node.@page == "507" && node.author.text() == "任玉刚"
}.collect {
    
    
    node -> return node.title.text()
}

println("name:$name")

1. Just call the findAll of the children method of the target node directly, and directly traverse the target node collection.
2. The depthFirst method can also use "*" instead

2. Generate xml file

(1) The xml to be generated

<LolPersons id='1'>
  <yasuo type='中单' desc='托儿索'>亚索</yasuo>
  <gailun type='上单' desc='战士'>盖伦</gailun>
</LolPersons>

(2) Static generation: the use of MarkupBuilder class

//xml 的生成
//public class StringWriter extends Writer

def sw = new StringWriter() // 生成的xml写入文件
def xmlBuilder = new MarkupBuilder(sw) // 生成xml的核心类

xmlBuilder.LolPersons(id:"1"){
    
    
    yasuo(type:"中单" ,desc:"托儿索","亚索")
    gailun(type:"上单" ,desc:"战士","盖伦")
}
println(sw)
----------------------------------------
log:
<LolPersons id='1'>
  <yasuo type='中单' desc='托儿索'>亚索</yasuo>
  <gailun type='上单' desc='战士'>盖伦</gailun>
</LolPersons>

1. Core class MarkupBuilder
2. Ideas:

1. First generate the root node and call the method (the method is named the root node name)
2. The node set node is, the method is hung in the closure.
3. The attribute and attribute value of the node can use the key-value pair
4. The node's The value can be used directly.

(2) Entity data filling (dynamic way)

1. Define entities
2. MarkupBuilder class to generate
ps:json is used more, here is one way.

Three, documents

The operation api groovy of java files can be used, butgroovy encapsulates the fileFaster operation

1. Read the file

Insert picture description here

Read this iml file in the project directory as shown in the figure

// 1、文件的读取(本工程下的一个iml文件)
def file = new File("../../HelloGroovy.iml")

// 遍历方式1(有点鸡肋)
file.eachLine {
    
    
    line -> println(line)
}

// 遍历方式2(快捷)
String text = file.getText()
println(file.getText())

println(file.readLines()) // 读取没行的结果放入了list集合中

// 遍历方式3:读取指定数据(前100个字符)

println(file.withReader {
    
    
    reader ->
        char[] buf = new byte[100]
        reader.read(buf)
        return buf
})

You can see the above three ways,Among them, file.getText() is the simplest, to get the text content of the file directly, Very suitable for reading text files.

2. Writing of documents
def newFile = new File("../../HelloGroovy2.iml")
if (!newFile.exists()) {
    
    
    newFile.createNewFile()

    newFile.withWriter {
    
    
        write -> write.append(file.getText())
    }
}

Copy the HelloGroovy2.iml file in the project directory, you
can seeOne sentence append() is written directly into the file

3. Serialization of objects: reading and writing objects
//1、保存对象

def saveObject(Object object, String path) {
    
    
    def file = new File(path)
    if (!file.exists()) {
    
    
        file.createNewFile()
    }
    file.withObjectOutputStream {
    
    
        objectStream -> objectStream.writeObject(objectStream)
    }
}

//2、 读对象

def readObject(String path) {
    
    
    def obj = null
    def file = new File(path)
    if (!file.exists() || file == null) {
    
    
        return
    }
    file.withObjectInputStream {
    
    
        readObject ->
            obj = readObject.readObject()
    }
    return obj
}
4. Summary

1. It can be seen that groovy extends the File class.
2. Through the withXXX closure method, you can obtain related objects for related operations (for example, reader, writer, ObjectInputStream, and other objects). These objects do not need to perform close operations.
3. Relevant objects can also be obtained through newXXX, which is equivalent to using java file classes and requires operations such as close.

end

I feel that the processing and packaging of the file is too awesome, and I don't want to use java after using it! ! ! !

Guess you like

Origin blog.csdn.net/qq_38350635/article/details/102647061