Groovy - 读取文件,修改其内容并将其返回

时间:2013-12-05 09:51:15

标签: groovy

我想知道读取文件的最佳方法是什么(我作为参数获得), 修改其中的特定行(遍历所有行,直到我找到我需要的那一行) 最后,保存新修改的文​​件而不是旧文件。

此致 伊戈尔。

1 个答案:

答案 0 :(得分:1)

您需要写入临时文件,然后重命名临时文件以覆盖原始文件:

// Path to the original file
def infile = 'in.txt'

// Create a temp file
def tmpFile = File.createTempFile( 'new', 'tmp' )

tmpFile.withWriter { w ->

    // for each line in the input file
    new File( infile ).eachLine { line ->

        // Modify the line if required
        if( line.endsWith( '2' ) ) {
            line = 'Modified'
        }

        // Write the line out to the temp file
        w << line << '\n'
    }
}

// Then rename the temp file to overwrite the original
tmpFile.renameTo( infile )
相关问题