简体   繁体   English

Groovy中的最后一行文件

[英]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. 我编写了一个Groovy脚本,可以通过它后面的空行识别每个块。 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? 如果可以,我该怎么办?

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++
    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++
  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 这两种方法基本上都会将空行数加起来,如果文件中的最后一行不是空白,则将计数增加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 {
  it.writeLine()
}

Of course, if you have multiple things writing to the same file at the same time, this will just generate a mess 当然,如果你有多个东西同时写入同一个文件,这只会产生一团糟

This is the first hit on google for last line of file groovy. 这是google最后一行文件groovy的第一个热门话题。 For those looking for a quick and easy way to get the last line : 对于那些寻找快速简便的方法来获得最后一行的人

    new(File("/home/user/somefile.txt").eachLine{
        if(it != null){
            lastLine = it
        }
    }

.eachLine iterates through each line of the text file and lastLine is set to the it variable until it's null. .eachLine遍历文本文件的每一行,并将lastLine设置为it变量,直到其为空。 Pretty straightforward 非常简单

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM