【发布时间】:2010-08-11 07:45:21
【问题描述】:
这是对此处提出的问题的跟进: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
有谁知道为什么要打印出重复的信息?
【问题讨论】:
-
标题是否总是以 ... 结尾?
-
标头结尾是:正在检查硬盘信息...起初我想也许我还需要在其后包含“\n\n”,但根本不返回任何数据。跨度>
-
您的代码对我有用...您确定这是您正在运行的代码吗?唯一的问题是您在最终的
if( driveInfo )之前缺少} -
我以为我在帖子中忘记了一个右括号,我确实做到了。但是,我并没有在我的代码中错过它,我应该 c+p'ed 它而不是输入它。上面的代码对你有用吗? (一旦添加了右括号)。我没有这么幸运,它看起来对我来说是正确的,这就是为什么我决定发布它来看看其他人是否知道它无法正常运行的原因。
-
是的,使用提供的测试数据并添加缺少的
},它会像在另一个问题中一样打印出 Drive 0 和 Drive 1,没有重复数据:-/