博客主页

接下来讲解Groovy高级用法,文件的处理。

File类

下面以示例的方式讲解File类中的方法,其中GDK新增方法有:

  1. void append(Object text) 将字符串text追加到文件末尾
  2. void eachFile(Closure closure) 为指定目录中的每个文件应用闭包
  3. void eachFileRecurse(Closure closure) 为指定目录中的每个文件应用闭包,且对每个子目录使用递归方法
  4. T eachLine(Closure closure) 逐行遍历指定的文档
  5. String getText() 读取文件内容并将它作为一个字符串返回
  6. T withPrintWriter(Closure closure) 为文件创建一个新的PrintWriter辅助方法,并将它传递给闭包,并再次确认问价是否关闭

示例一:以一次一行的方式读取并显示文件

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.

示例二:目录列表,listDir功能可以使用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)

示例三:文件拷贝

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)
    }
}

实例四:对象的读写

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

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

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

// 写入Person对象
file.withObjectOutputStream { outStream ->
   outStream.writeObject(person)
}

// 从文件中读取Person对象
file.withObjectInputStream { inStream ->
   def p = (Person) inStream.readObject()
    println "name:${p.name}, age:${p.age}"
}

json操作详解

实体对象转为json,通过JsonOutput类完成,可以调用prettyPrint方法输出标准json格式

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

// 实体对象转化为json
def json = JsonOutput.toJson(persons)
// [{"age":123,"name":"kerwin"},{"age":456,"name":"xujinbing"}]
println json

// prettyPrint方法可以标准json格式输出
println JsonOutput.prettyPrint(json)

json转化为实体对象,通过JsonSlurper类完成

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操作详解

首先定一个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格式数据的解析通过XmlSlurper完成

 def xmlSlurper = new XmlSlurper()
 def response = xmlSlurper.parseText(xml)
 println response.value.books[0].book[0].title.text() // 疯狂Android讲义
 println response.value.books[0].book[0].author.text() // 李刚
 println response.value.books[0].book[0].@available  // 20
 
 // 遍历作者是`李刚`的书籍
 def list = []
 response.value.books.each { books ->
    books.book.each { book ->
        def author = book.author.text()
        if (author == '李刚') list.add(book.title.text())

    }
}
println list.toListString()
// [疯狂Android讲义, Vue从入门到精通]

深度遍历和广度遍历xml数据

 /**
  * 深度遍历xml数据
  */
 // 查询作者是`李刚`的书籍
 def books = response.depthFirst().findAll { book ->
     return book.author.text() == '李刚'
 }
 println books.toListString()
 // [疯狂Android讲义李刚, Vue从入门到精通李刚]

/**
 * 广度遍历xml数据
 */
// 查询id=2的书名
def titles = response.value.books.children().findAll { node ->
    node.name() == 'book' && node.@id == '2'
}.collect { node ->
    return node.title.text()
}
println titles.toListString()

生成xml格式数据,通过MarkupBuilder类完成

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

FileWriter writer = new FileWriter(file)

/**
 * 写入data.xml文件中数据
 *
 * <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')
    }
}

如果我的文章对您有帮助,不妨点个赞鼓励一下(^_^)


小兵兵同学
56 声望23 粉丝

Android技术分享平台,每个工作日都有优质技术文章分享。从技术角度,分享生活工作的点滴。