且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Groovy脚本逐行修改文本文件

更新时间:2023-12-05 16:53:46

AFAIK,您只能在文件末尾附加文本.

AFAIK in Groovy you can only append text at the end of the file.

因此,在处理完每一行后,需要在每行上添加',您需要重写整个文件.

Hence to add ' on each line when it is processed you need to rewrite the entire file.

您可以使用以下方法,但是由于您要加载内存中的所有行,因此我建议您仅将其用于较小的文件.总之,您的问题的解决方法可能是:

You can use the follow approach but I only recommend you to use for a small files since you're loading all the lines in memory. In summary an approach for your question could be:

// 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
}

避免对大型文件加载内存中所有行的***方法是使用读取器读取文件内容,并使用带有写入器的临时文件写入结果,而优化版本可能是:

An optimal approach to avoid load all lines in memory for a large files is to use a reader to read the file contents, and a temporary file with a writer to write the result, and optimized version could be:

// 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
}