美文网首页
文件操作

文件操作

作者: 龙剑灵 | 来源:发表于2020-03-20 00:52 被阅读0次
def file = new File('t.iml')
file.eachLine {
    line -> println line
}
println "--------------------1--------------------------"
def text = file.getText()
println text
println "--------------------2--------------------------"

def result = file.readLines()
result.each { println it.toString()}
println "---------------------3--------------------------"
//读取文件部分内容
def reader = file.withReader { reader ->
    char[] buffer = new char[100]
    reader.read(buffer)
    return buffer
}
println reader //只输出前100个字符

文件的复制

def rs = copy('t.iml', 't2.iml')
def copy(String sourcePath, String targetPath) {
    try {
        //首先创建目标文件
        def targetFile = new File(targetPath)
        if (!targetFile.exists()) {
            targetFile.createNewFile()
        }
        //开始copy
        new File(sourcePath).withReader { read ->
            def lines = read.readLines()
            targetFile.withWriter { writer ->
                lines.each { line ->
                    writer.append(line).append("\n")
                }
            }
        }
        return true
    } catch (Exception e) {
    }
}

文件的读写

println saveObject(new LawCase(id: "199", name: "jimmy"), "case.bin")
//对象的读写
def saveObject(Object obj, String targetPath) {
    try {
        //首先创建目标文件
        def targetFile = new File(targetPath)
        if (!targetFile.exists()) {
            targetFile.createNewFile()
        }
        targetFile.withObjectOutputStream { out ->
            out.writeObject(obj)
        }
        return true;
    } catch (Exception e) {
    }
    return false
}

println readObject("case.bin")

static def readObject(String path) {
    def obj = null
    try {
        //首先创建目标文件
        def file = new File(path)
        if (file == null || !file.exists()) {
            return null
        }
        file.withObjectInputStream { input ->
            obj = input.readObject()
        }
    } catch (Exception e) {

    }
    return obj
}

相关文章

  • 文件操作

    文件操作 目标 文件操作的作用 文件的基本操作打开读写关闭 文件备份 文件和文件夹的操作 一. 文件操作的作用 思...

  • 文件和目录处理相关

    文件和目录处理相关 题: 考点:文件操作/写入操作; 延伸:目录操作函数,其他文件操作; 文件读写操作 文件系统函...

  • 09-文件操作

    一、文件操作流程 a.普通文件操作流程: 打开文件 操作文件 关闭文件 b. json文件操作流程: open(文...

  • VBS文件操作

    VBS文件操作'操作文本文件,操作fso对象(文件对象操作) --------------------------...

  • 文件操作

    文件操作:打开文件、读写文件、操作文件内容 写入文件操作:(把大象装入冰箱)1.打开文件 ...

  • 类的补充

    一.复习 1.文件操作a.操作流程:打开文件(open),操作文件,关闭文件with open() as 文件变量...

  • 文件

    目标 文件操作的作用 文件的基本操作打开读写关闭 文件备份 文件和文件夹的操作 一. 文件操作的作用 思考:什么是...

  • 16总 正则表达式

    复习: 1.文件操作a.操作流程: 打开文件(open) --- 操作文件 --- 关闭文件(close)with...

  • 2018-09-10

    01-recode 1.文件操作a.操作流程:打开文件---》操作文件----》关闭文件with open() ...

  • 2018-09-10 day16总结

    1.文件操作 a.操作流程:打开文件(open)-操作文件-关闭文件(close)with open() as 文...

网友评论

      本文标题:文件操作

      本文链接:https://www.haomeiwen.com/subject/bjcdyhtx.html