Groovy脚本逐行修改文本文件

时间:2016-09-13 12:58:36

标签: file groovy soapui

我有一个输入文件,Groovy文件从中读取输入。处理完特定输入后,Groovy脚本应该能够对它使用的输入行进行注释,然后继续。

文件内容:

1   
2        
3

当它处理第1行和第2行时,输入文件将如下所示:

'1    
'2                   
3

通过这种方式,如果我重新运行Groovy,我想从它上次停止的行开始。如果使用了输入且输入失败,则不应对该特定行进行注释('),以便可以尝试重试。

感谢您是否可以帮助草拟Groovy脚本。

由于

1 个答案:

答案 0 :(得分:1)

Groovy 中的AFAIK只能在文件末尾附加文本。

因此,在处理每行时添加',您需要重写整个文件。

您可以使用以下方法,但我只建议您使用小文件,因为您正在加载内存中的所有行。总之,您的问题的方法可能是:

// open the file
def file = new File('/path/to/sample.txt')
// get all lines
def lines = file.readLines()

try{
    // for each line
    lines.eachWithIndex { line,index ->
        // if line not starts with your comment "'"
        if(!line.startsWith("'")){
            // call your process and make your logic...
            // but if it fails you've to throw an exception since
            // you can not use 'break' within a closure
            if(!yourProcess(line)) throw new Exception()

            // line is processed so add the "'"
            // to the current line
            lines.set(index,"'${line}")
        }
     }
}catch(Exception e){
  // you've to catch the exception in order
  // to save the progress in the file
}

// join the lines and rewrite the file
file.text = lines.join(System.properties.'line.separator')

// define your process...
def yourProcess(line){
    // I make a simple condition only to test...
    return line.size() != 3
}

避免为大文件加载内存中所有行的最佳方法是使用读取器读取文件内容,使用写入器写入结果的临时文件,优化版本可以是:

// open the file
def file = new File('/path/to/sample.txt')

// create the "processed" file
def resultFile = new File('/path/to/sampleProcessed.txt')

try{
    // use a writer to write a result
    resultFile.withWriter { writer ->
        // read the file using a reader 
        file.withReader{ reader ->
            while (line = reader.readLine()) {

                // if line not starts with your comment "'"
                if(!line.startsWith("'")){

                    // call your process and make your logic...
                    // but if it fails you've to throw an exception since
                    // you can not use 'break' within a closure
                    if(!yourProcess(line)) throw new Exception()

                    // line is processed so add the "'"
                    // to the current line, and writeit in the result file
                    writer << "'${line}" << System.properties.'line.separator'
                }    
            }
        }
    }

}catch(Exception e){
  // you've to catch the exception in order
  // to save the progress in the file
}

// define your process...
def yourProcess(line){
    // I make a simple condition only to test...
    return line.size() != 3
}