gpt4 book ai didi

java - 选择第二列(FileReader)

转载 作者:行者123 更新时间:2023-12-01 09:06:14 24 4
gpt4 key购买 nike

我正在循环 csv。我有两个问题:

1)我按名称选择第二列,例如

if(tab[1].equals("Col2")

我不想输入列的名称。我只想选择第二列。

2)如何跳过第一行(标题)

以下是循环 csv 的代码示例:

String csvFile = "C:\\test.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";

try{
br = new BufferedReader(new FileReader(csvFile));

while ((line = br.readLine()) != null) {
String[] tab=line.split(cvsSplitBy);

int tmp;
if(tab[1].equals("Col2")){

tmp = Integer.parseInt(tab[2]);

for(int i=0;i<tmp;i++){
// TO DO
}
}
}
}

最佳答案

最好使用 CSVReader 为此,它提供了大量用于处理 csv 文件的 API。当然,这是一个完整的工作代码,没有异常处理。

String csvFile = "C:\\test.csv";
CSVReader reader;
String[] nextRow;
char cvsSplitBy = ';';

try {

//Last argument will determine how many lines to skip. 1 means skip header
reader = new CSVReader(new FileReader(csvFile), cvsSplitBy, CSVParser.DEFAULT_QUOTE_CHARACTER, 1);

while ((nextRow = reader.readNext()) != null) {

if(nextRow.length > 2){
//nextRow[1] will always give second column value
int tmp = Integer.parseInt(nextRow[1]);
for (int i = 0; i < tmp; i++) {
// TO DO
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

关于java - 选择第二列(FileReader),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41264288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com