blaughli blaughli - 1 year ago 176
Groovy Question

Last Line of File in Groovy

Based on my research, reading the last line of a text file seems complicated. I've got a text file that essentially consists of blocks of lines, each block separated by a blank line. I wrote a Groovy script that can recognize each block by the blank line following it. I'm trying to count the paragraphs.

My issue is that my last block is not followed by a blank line (these blocks are generated by another program, they're not just files I've typed)

I was thinking that I might get around this "read the last line of file" problem by just appending a blank line to the end of my file, and then running my script. Is this smart, or is it just as hard as reading the last line?

If it could work, how might I do it?

Answer Source

As far as I can think, you have 2 options.

If you can load the whole file into memory, you can do something like:

int countBlocksInMem( File f ) {
  f.readLines().with { lines ->
    int size = lines.grep { it == '' }.size()
    if( lines[ -1 ] != '' ) size++

If it's too big to be loaded into memory, you could do:

int countBlocks( File f ) {
  String lastLine
  int size = 0
  f.eachLine { line ->
    lastLine = line
    if( !line ) size++
  if( lastLine ) size++

Both methods basically add up the number of blank lines, and if the last line in the file is not blank, increment the count by 1

Edit after question was completely changed

To append a blank line to a file, you can just do:

new File( 'file.txt' ) << '\n'

Or, with a writer

new File( 'file.txt' ).withWriterAppend {

Of course, if you have multiple things writing to the same file at the same time, this will just generate a mess

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download