尝试读取 csv 文件的第二列时出现 NullPointerException

NullPointerException when trying to read second column of a csv file

下面的代码读取了一个包含两列的 csv 文件。如果您查看被注释掉的 for 循环,代码会在它从第一列检索所有数据行的地方工作。但是,当我尝试为从第二列中选择的另一个循环实现相同的操作时,我得到一个 'Null Pointer Exception'.

如果我将值从 [1] 更改为 [0],我会注意到未注释的 for 循环。它有效,但显然我需要 [1] 从第二列中选择。

我已经尝试创建两个单独的 csv 文件并从那里开始,但仍然遇到同样的错误。

代码如下:

def test1array_properties = [];
def test2array_properties = [];

for(int i = 0; i <= test1_properties.size(); i++) {
        if(!test1_properties[i][0]) {
        break
    } else {
        log.info test1_properties[i][0]
        test1array_properties << test1_properties[i][0]
    }

}


for(int i = 0; i <= test2_properties.size(); i++) {
    if(!test2_properties[i][1]) {
        break
    } else {
        log.error test2_properties[i][1]
        test2array_properties << test2_properties[i][1]
    }

}

这里是 groovy 脚本,用于将所需数据放入相应的变量中。

这不使用任何库,只是 groovy。

//This assumes both villas, hotels in the csv file
//Change file name if needed;use absolute path or use property expansion to make it work on other machines.

def filename = 'VillasAndBeach.csv'
def lines = new File(filename).readLines()
def villas = []
def hotels = []
lines.eachWithIndex { line, index ->
    if (index) {
        def data = line.split(',')*.trim()
        if (data[0]) villas << data[0]
        if (data[1]) hotels << data[1]
    }
}

log.info "Villas : ${villas}"
log.info "Hotels: ${hotels}"