Groovy advanced usage (3): file, XML, JSON processing

Time:2020-3-25

Blog Homepage

Next, I’ll talk about groovy’s advanced usage and file processing.

Class File

Here is an example to explain the methods in the file class. The new GDk methods are:

  1. void append(Object text)Append string text to the end of the file
  2. void eachFile(Closure closure)Apply closure for each file in the specified directory
  3. void eachFileRecurse(Closure closure)Applies a closure to each file in the specified directory, using a recursive method for each subdirectory
  4. T eachLine(Closure closure)Traverse the specified document line by line
  5. String getText()Read the contents of the file and return it as a string
  6. T withPrintWriter(Closure closure)Create a new printwriter helper method for the file, pass it to the closure, and confirm again if price inquiry is closed

Example 1: reading and displaying files one line at a time

File file = new File('D:\work\mycode\gradle\groovyLearn\src\readme.md')
file.eachLine { String line -> 
    println "line: ${line}"
}

//line: this is the first line.
//line: this is the second line.
//line: this is the third line.
//line: this is the fourth line.

Example 2: directory list, listdir function can be implemented with eachfilerecurse

def listDir(File dirFile) {
    dirFile.eachFile { File file ->
        println "${file.getAbsolutePath()}"
        if (file.isDirectory()) listDir(file)
    }
}

File dir = new File('D:\work\mycode\gradle\groovyLearn\src')
listDir(dir)

Example 3: file copy

File srcFile = new File('D:\work\mycode\gradle\groovyLearn\src\readme.md')
println "srcFile is exists: ${srcFile.exists()}"
 
File destFile = new File('D:\work\mycode\gradle\groovyLearn\src\backup.md')
println "destFile is exists: ${destFile.exists()}"
if (!destFile.exists()){
    destFile.createNewFile()
} else {
    destFile.delete()
}

destFile.withPrintWriter { PrintWriter writer ->
    srcFile.eachLine { String line ->
       writer.println(line)
    }
}

Example 4: reading and writing of objects

def person = new Person(name: 'kerwin', age: 23)

def file = new File('../../../../person.bin')

if (!file.exists()) file.createNewFile()

//Write person object
file.withObjectOutputStream { outStream ->
   outStream.writeObject(person)
}

//Read person object from file
file.withObjectInputStream { inStream ->
   def p = (Person) inStream.readObject()
    println "name:${p.name}, age:${p.age}"
}

JSON operation details

The entity object is converted to JSON throughJsonOutputClass. You can call the prettyprint method to output the standard JSON format

def persons = [new Person(name: 'kerwin', age: 123),
              new Person(name: 'xujinbing', age: 456)]

//Entity object converted to JSON
def json = JsonOutput.toJson(persons)
// [{"age":123,"name":"kerwin"},{"age":456,"name":"xujinbing"}]
println json

//The prettyprint method can be output in standard JSON format
println JsonOutput.prettyPrint(json)

JSON is converted to entity object throughJsonSlurperClass completion

def jsonString = '''
[
    {
        "age": 123,
        "name": "kerwin"
    },
    {
        "age": 456,
        "name": "xujinbing"
   }
]
'''
def jsonSlurper = new JsonSlurper()
def persons = jsonSlurper.parseText(jsonString)
println persons
// [[age:123, name:kerwin], [age:456, name:xujinbing]]

println "name: ${persons[0].name}, age: ${persons[0].age}"
//name: kerwin, age: 123

XML operation details

First, define an XML data format

final String xml = '''
   <response version-api="2.0">
        <value>
            <books id="1" classification="android">
                <book available="20" id="1">
                    < title > crazy Android handout < / Title >
                    < author id = "1" > Li Gang < / author >
                </book>
                <book available="14" id="2">
                   < title > first line code < / Title >
                   < author id = "2" > Guo Lin < / author >
               </book>
               <book available="13" id="3">
                   < title > Android development art exploration
                   < author id = "3" > Ren Yugang < / author >
               </book>
               <book available="5" id="4">
                   < title > Android source code design mode < / Title >
                   < author id = "4" > he Honghui < / author >
               </book>
           </books>

           <books id="2" classification="web">
               <book available="10" id="1">
                   < title > Vue from entry to mastery
                   < author id = "4" > Li Gang < / author >
               </book>
           </books>
       </value>
    </response>
'''

XML format data analysis passedXmlSlurpercomplete

def xmlSlurper = new XmlSlurper()
 def response = xmlSlurper.parseText(xml)
 Println response. Value. Books [0]. Book [0]. Title. Text() // crazy Android handout
 Println response. Value. Books [0]. Book [0]. Author. Text() // Li Gang
 println response.value.books[0].book[0][email protected]  // 20
 
 //Ergodic author is Li Gang's book
 def list = []
 response.value.books.each { books ->
    books.book.each { book ->
        def author = book.author.text()
        If (author = = 'Li Gang') list. Add (book. Title. Text())

    }
}
println list.toListString()
//[crazy Android handout, Vue from entry to mastery]

Depth traversal and breadth traversal of XML data

/**
  *Deep traversal of XML data
  */
 //The author is Li Gang's book
 def books = response.depthFirst().findAll { book ->
     Return book. Author. Text() = = 'Li Gang'
 }
 println books.toListString()
 //[crazy Android handout Li Gang, Vue from getting started to mastering Li Gang]

/**
 *Breadth traversal XML data
 */
//Query the title of the book with id = 2
def titles = response.value.books.children().findAll { node ->
    node.name() == 'book' && [email protected] == '2'
}.collect { node ->
    return node.title.text()
}
println titles.toListString()

Generate XML format data throughMarkupBuilderClass completion

def file = new File('../../../../data.xml')
if (!file.exists()) file.createNewFile()

FileWriter writer = new FileWriter(file)

/**
 *Write data to data.xml file
 *
 * <books classification='android'>
 *   <book id='1'>
 *     <title>Groovy</title>
 *     <authpr>kerwin</authpr>
 *   </book>
 * </books>
 */
def builder = new MarkupBuilder(writer)
builder.books(classification: 'android') {
    book(id: '1') {
        title('Groovy')
        authpr('kerwin')
    }
}

If my article is helpful to you, please give me a compliment

Recommended Today

NPM you don’t know

Introduction Act asnodeThe package manager tool, which comes with thenodejsCommunity andWeb front end EngineeringIn the context of growing field development,npmIt has become a necessary tool for each front-end development student. Every day, countless developers usenpmTo build the project,npm init、npm installBut most of the students only use NPMnpm installHere. (trust to deletenode_modulesFolders, re executingnpm installYou should […]