2016-09-13 29 views
0

我有一個輸入文件,Groovy文件從中讀取輸入。一旦處理了特定的輸入,Groovy腳本應該能夠評論它使用的輸入行,然後繼續。Groovy腳本按行修改文本文件

文件內容:

1 
2   
3 

當處理線1和線2,輸入文件看起來如下:

'1  
'2     
3 

通過這種方式,如果我重新運行的Groovy,我想從上次停止的路線開始。如果使用了輸入並且失敗了,則該特定行不應被評論('),以便可以嘗試重試。

欣賞如果你能幫忙起草Groovy腳本。

感謝

+0

也許嘗試一些東西,告訴我們你有什麼,我們可以提供幫助。也許有通讀[問]。 – SiKing

+0

@sshark分享你的代碼,讓你有更多的機會得到答案 – user1207289

回答

1

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 
} 
+0

嗨,感謝堆腳本。這正是我想要的。不幸的是我需要處理更大的輸入文件(5000行)。不確定這是否會成爲您建議的問題。我正在考慮將處理後的行寫入新文件(追加)。顯然它需要手動再次輸入錯誤的輸出文件作爲輸入 – sshark

+0

@sshark 5000行與命令(我想你的文件平均少於100kb,但也可能更多)在這種情況下,它是完全沒問題的IMO使用這種方法沒有問題。 – albciff

+0

謝謝你們,非常感謝您的及時幫助 – sshark