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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章