Groovy parsing text file

前端 未结 2 551
醉话见心
醉话见心 2020-12-28 20:41

I have a file log that I would like to parse and am having some issues. At first it seemed it would be simple. I\'ll go ahead and post the source I have come up with and the

2条回答
  •  一向
    一向 (楼主)
    2020-12-28 21:18

    Here is my solution:

    File file = new File('testdata.txt')
    if(file.exists()) {
        def drives = [[:]]
        // Split each line using whitespace:whitespace as the delimeter.
        file.splitEachLine(/\s:\s/) { items ->
            // Lines that did not have the delimeter will have 1 item.
            // Add a new map to the end of the drives list.
            if(items.size() == 1 && drives[-1] != [:]) drives << [:]
            else {
                // Multiple assignment, items[0] => key and items[1] => value
                def (key, value) = items
                drives[-1][key] = value
            }
        }
    
        drives.eachWithIndex { drive, index ->
            println "Drive $index"
            drive.each {key, value ->
                println "\t$key: $value"
            }
        }
    }
    

提交回复
热议问题