Groovy读取文本文件但省略标题

时间:2010-08-11 07:45:22

标签: file groovy header

这是对此处提出的问题的跟进:Groovy parsing text file

现在的区别是我的文件有一个标题,我试图首先阅读标题,然后阅读我想要的内容,但由于某种原因它似乎没有合作。

def dataList = []
def theInfoName = 'testdata.txt'
boolean headersDone = false    //header set to false by default

File theInfoFile = new File( theInfoName )

if( !theInfoFile.exists() ) {
  println "File does not exist"
} else {
  def driveInfo = [:]
  // Step through each line in the file
  theInfoFile.eachLine { line ->

  //this is where im trying to account for the header
  if(!headersDone) {      //look if line contains "..." if it does that turn headersDone to true
   if(line.contains("...")) {
     headersDone = true
   }
  } else {
     // If the line isn't blank
     if( line.trim() ) {
       // Split into a key and value
       def (key,value) = line.split( '\t: ' ).collect { it.trim() }
       // and store them in the driveInfo Map
       driveInfo."$key" = value
     }
     else {
       // If the line is blank, and we have some info
       if( driveInfo ) {
         // store it in the list
         dataList << driveInfo
         // and clear it
        driveInfo = [:]
       }
     }
  }
  // when we've finished the file, store any remaining data
  if( driveInfo ) {
    dataList << driveInfo
  }
}

dataList.eachWithIndex { it, index ->
  println "Drive $index"
  it.each { k, v ->
    println "\t$k = $v"
  }
}

我使用上一篇文章中提供的代码尝试了它,以确保它不是我做的不同而且它带有相同的输出。

它会发布11次相同的信息块。

标题看起来如下:

Random date information here with some other info
Slightly more random information followed by

Examining hard disk information ...

HDD Device 0 : /dev/sda
HDD Model ID  : ST3160815A
HDD Serial No : 5RA020QY
HDD Revision  : 3.AAA
HDD Size     : 152628 MB
Interface    : IDE/ATA
Temperature         : 33 C
Health  : 100%
Performance  : 70%
Power on Time : 27 days, 13 hours
Est. Lifetime : more than 1000 days

HDD Device 1 : /dev/sdb
HDD Model ID  : TOSHIBA MK1237GSX
HDD Serial No : 97LVF9MHS
HDD Revision  : DL130M
HDD Size     : 114473 MB
Interface    : S-ATA
Temperature  : 30 C
Health  : 100%
Performance  : 100%
Power on Time : 38 days, 11 hours
Est. Lifetime : more than 1000 days

有谁知道为什么打印出重复的信息?

2 个答案:

答案 0 :(得分:2)

问题是在driveInfo添加了“最后一个”dataList

// when we've finished the file, store any remaining data
if( driveInfo ) {
   dataList << driveInfo
}

它必须是当前位置下方的一个大括号,否则它属于eachLine闭包。

答案 1 :(得分:0)

看不到任何明显错误的代码。我建议添加几个println,以便您可以看到地图,列表和变量的变化情况。这可能会让你知道bug可能在哪里。