【发布时间】:2015-12-28 04:40:21
【问题描述】:
假设我有这样的 CSV 文件:
Football Contest blabla bla,,,,,,,
Team number1,Team number2,Points team1,Points team2,Red cards
Sweden,France,1,2,"
Sweden,Brazil,3,5,2
Sweden,Germany,2,2,3
Sweden,Spain,3,5,"
在这个文件中,我只想打印出红牌的比赛。所以在这个例子中我想打印:
瑞典 - 巴西 = 2 瑞典 - 德国 = 3
这是我当前的代码,我坚持如何继续。
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String lines = br.readLine();
String result[] = lines.split(",");
do{
System.out.println();
}while((lines = br.readLine()) != null);
//String result[] = lines.split(",");
//System.out.println(result[1]);
br.close();
}catch (FileNotFoundException e){
System.out.println("File not found : "+ file.toString());
}catch (IOException e ){
System.out.println("Unable to read file: "+ file.toString());
}
编辑我得到了帮助:
while (line != null) {
String result[] = line.split(",");
if (result.length == 5) { //red cards present?
System.out.println(result[0] + " - " + result[1] + " " + result[4]);
}
line = br.readLine(); //read next
}
但我现在遇到的问题是,由于 csv 文件中的“”,它仍然会全部打印出来。为什么我不能做这样的事情?
if (result[4] == "1,2,3,4,5" ){
System.out.println(result[0] + " - " + result[1] + " " + result[4]);
}
【问题讨论】:
-
逐行读取,然后 line.split(","),分析值并输出您需要的内容
-
要正确解析 CSV,请使用 opencsv 等库。否则,您将重新发明分词器和解析器。所有使用正则表达式和/或 split() 的建议都会产生无法处理 CSV 的所有有效表示的脆弱代码。