我有一個輸入文件,Groovy文件從中讀取輸入。一旦處理了特定的輸入,Groovy腳本應該能夠評論它使用的輸入行,然後繼續。Groovy腳本按行修改文本文件
文件內容:
1
2
3
當處理線1和線2,輸入文件看起來如下:
'1
'2
3
通過這種方式,如果我重新運行的Groovy,我想從上次停止的路線開始。如果使用了輸入並且失敗了,則該特定行不應被評論('
),以便可以嘗試重試。
欣賞如果你能幫忙起草Groovy腳本。
感謝
我有一個輸入文件,Groovy文件從中讀取輸入。一旦處理了特定的輸入,Groovy腳本應該能夠評論它使用的輸入行,然後繼續。Groovy腳本按行修改文本文件
文件內容:
1
2
3
當處理線1和線2,輸入文件看起來如下:
'1
'2
3
通過這種方式,如果我重新運行的Groovy,我想從上次停止的路線開始。如果使用了輸入並且失敗了,則該特定行不應被評論('
),以便可以嘗試重試。
欣賞如果你能幫忙起草Groovy腳本。
感謝
AFAIK在Groovy中你只能在文件的末尾添加文本。
因此,在處理每行時要添加'
,您需要重寫整個文件。
您可以使用以下方法,但我只建議您使用小文件,因爲您正在加載內存中的所有行。總之你的問題的方法可能是:
// 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
}
也許嘗試一些東西,告訴我們你有什麼,我們可以提供幫助。也許有通讀[問]。 – SiKing
@sshark分享你的代碼,讓你有更多的機會得到答案 – user1207289