3、Groovy对文件读与写操作

1、创建实体类

package com.groovy.model
/**
 * 在Groovy不需要自定义构造方法.但是必须要指定属性名称去传参数数据,Groovy会自动创建,在调用的时候会自动生成setter/getter方法
 */
class User implements Serializable{
    //用户Id
    Long userId
    //用户名
    String userName
    //年龄
    int  age
}

2、创建测试test.txt文件

  • 在工程的Resource资源文件夹里面创建此文件即可在程序读取,文件内容有自己指定.
A multi-faceted language for the Java platform
Apache Groovy is a powerful, optionally typed and dynamic language, with static-typing and static compilation capabilities,for the Java platform aimed at improving developer productivity thanks to a concise, familiar and easy to learn syntax.
It integrates smoothly with any Java program, and immediately delivers to your application powerful features, includingscripting capabilities, Domain-Specific Language authoring, runtime and compile-time meta-programming and functional programming.

2、测试类

package com.groovy.domain
import com.groovy.model.User
import org.junit.Test
class FileTest {

    @Test
    void testReader1() {
        //直接读取项目resource目录的指定文件名称
        def baseDir = FileTest.getClassLoader().getResource("test.txt").getPath()
        /**
         * 循环读取每一行进行读取.
         */
        new File(baseDir).eachLine { line, nb ->
            println "Line $nb: $line"
        }
    }

    @Test
    void testReader2() {
        //指定路径目录,在指定文件名进行读取,此时的路径必须要知道在哪里
        def baseDir = "D:/devsoft/idea-workspace/groovy/out/production/resources/"

        /**
         * 循环读取每一行进行读取.
         */
        new File(baseDir, "test.txt").eachLine { line, nb ->
            println "Line $nb: $line"
        }
    }
    @Test
    void testReader3() {
        //直接读取项目resource目录的指定文件名称
        def baseDir = FileTest.getClassLoader().getResource("test.txt").getPath()

        /**
         * 一次性获取文件所有内容,并指定编码
         */
        def fileText = new File(baseDir).getText("utf-8")
        println(fileText)
    }

    @Test
    void testWriter1() {
        // 此时会在项目工程的groovy/out/production/resources/目录先对test.txt文件操作
        // 建议指定一个磁盘目录,然后在指定文件名称进行写入,如:testWriter2
        def baseDir = FileTest.getClassLoader().getResource("test1.txt").getPath()
        /**
         * 循环读取每一行进行读取.
         */
        new File(baseDir).withWriter("utf-8") { writer ->
            writer.writeLine 'Hello Groovy'
        }
    }

    @Test
    void testWriter2() {
        def baseDir = "D:/test/"

        /**
         * 指定一个磁盘文件目录,并且指定一个文件test1.txt名称进行写入内容
         */
        new File(baseDir, "test1.txt").withWriter("utf-8") { writer ->
            writer.writeLine 'Hello Groovy'
        }
    }

    /**
     * 拷贝文件内容,从一个文件拷贝内容到另外一个文件
     * @param sourcePath
     * @param dstPath
     */
    def copyFile(String sourcePath, String dstPath) {
        try {
            //判断不存在就,创建文件目录
            def dstFile = new File(dstPath)
            if (!dstFile.exists()) {
                dstFile.createNewFile()
            }
            //开始拷贝
            new File(sourcePath).withReader { reader ->
                //一次性读取所有信息
                def lines = reader.readLines()
                //写入目标文件
                dstFile.withWriter { writer ->
                    lines.forEach { line ->
                        //写入目标文件并且换行
                        writer.append(line).append("\r\n")
                    }
                }
            }
            return true
        } catch (Exception ex) {
            ex.printStackTrace()
        }
        return false
    }

    /**
     * 保存Object
     * @param obj
     * @param path
     */
    def saveObject(Object obj, String path) {
        try {
            def dstFile = new File(path)
            if (!dstFile.exists()) {
                dstFile.createNewFile()
            }
            dstFile.withObjectOutputStream {
                it.writeObject(obj)
            }
            return true
        } catch (Exception ex) {
            ex.printStackTrace()
        }
        return false
    }

    /**
     * 读取对象数据
     * @param path
     */
    def readObject(String path) {
        def obj = null
        try {
            def dstFile = new File(path)
            if (dstFile == null || !dstFile.exists()) return null
            //读取对象数据出来
            dstFile.withObjectInputStream {
                obj = it.readObject()
            }
        } catch (Exception ex) {
            ex.printStackTrace()
        }
        return obj
    }

   @Test
    void testReaderObject() {
          //读取出来并转换成User对象,语法与Kotlin类似
        def user = readObject("user.bin") as User
        println("userName=${user.userName},age=${user.age}")
    }

    @Test
    void testWriterObject() {
        def result = saveObject(user, "user.bin")
        println(result ? "成功" : "失败")
    }

}

3、testReader1与testReader2运行的结果

4、testWriter1与与testWriter2运行的结果

5、testWriterObject运行的结果

6、testReaderObject运行的结果

userName=周伯通,age=110
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章