读取CSV文件并使用Groovy将结果放入地图中(不使用任何外部库)

时间:2018-04-05 14:53:43

标签: groovy

我有一个如下所示的CSV文件:

斯诺,服务,操作ResponseTimeLimit
1,ProposalService,UPSERT,50
2,ScheduleService,getReservation,10个
3,ScheduleService,bookAppointment,23

我想将此结构作为地图列表,如下所示:

[
[Sno:“1”,服务:“ProposalService”,操作:“upsert”,ResponseTimeLimit:“50”], [斯诺: “2”,服务: “ScheduleService”,操作: “getReservation”,ResponseTimeLimit: “10”], [斯诺: “3”,服务: “ScheduleService”,操作: “bookAppointment”,ResponseTimeLimit: “23”]
]

我使用CSVReader(OpenCSV)获得了解决方案。但是,如果不使用任何外部引用/库(如openCSV等),我可以这样做吗?

2 个答案:

答案 0 :(得分:0)

如果CSV文件的结构始终相同,则可以使用Groovy脚本执行此操作:

def mapList = []

File csvFile = new File("/path/to/your/file.csv")

csvFile.eachLine { line ->
    def parts = line.split(",")
    def tmpMap = [:]

    tmpMap.putAt("Sno", parts[0])
    tmpMap.putAt("Service", parts[1])
    // etc.

    mapList.add(tmpMap)
}

答案 1 :(得分:0)

下面是迭代 csv 文件所有行的另一种方法:

def mapList = []
def headers = []
new File("/path/to/your/file.csv").readLines().eachWithIndex { row, rowIndex ->
    if (rowIndex == 0) { headers = row.split(',') }
    else {
        def tmpMap = [:]
        def cells = row.split(',').eachWithIndex { cell, cellIndex ->
          tmpMap[headers[cellIndex]] = cell
        }
        mapList.add(tmpMap)
    }
}

mapList 结果:

[[Sno:1, Service:ProposalService, Operation:upsert, ResponseTimeLimit:50], [Sno:2, Service:ScheduleService, Operation:getReservation, ResponseTimeLimit:10], [Sno:3, Service:ScheduleService, Operation:bookAppointment, ResponseTimeLimit:23]]
[Finished in 1.647s]`