Java比较csv文件值



我正试图创建一个csv文件,其中每行只显示一个团队名称,因此当您单击两次按钮时,它只会在团队名称不存在的情况下添加该名称。目前它添加了团队";UWE";每次按下按钮。其代码如下:

public void showStats(ActionEvent event){
try {
File matchFile = new File("src/sample/matchData.csv");
File scoreFile = new File("src/sample/scoreData.csv");
Scanner matchReader = new Scanner(matchFile);
Scanner scoreReader = new Scanner(scoreFile);
while (matchReader.hasNextLine()) {
String data = matchReader.nextLine();
List<String> matchList = Arrays.asList(data.split(","));
while (scoreReader.hasNextLine()) {
String dataScore = scoreReader.nextLine();
List<String> dataScoreList = Arrays.asList(dataScore.split(","));
if (dataScoreList.get(0).equals(matchList.get(0))) {
//
} else {
writeExcel("scoreData", matchList.get(0)) ;
}
System.out.println(dataScoreList);
}
System.out.println(matchList);
}
matchReader.close();
scoreReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

csv文件";matchData";包含:UWE、KCC、Jin、Julia、Chris、Ryan、1,1,1,1,1,1,0,0,0,00,0,0,0,1,1,0,5,0

csv文件";scoreData";中有一条空线

您可以首先浏览源CSV文件,并在映射中只放置包含唯一团队密钥的行。。。。

while (matchReader.hasNextLine()) {
String data = matchReader.nextLine();
String[] record = data.split(",", 2);
Map<String, String> matchList = new TreeMap<>();
matchList.putIfAbsent(record[0], record[1]); // only unique keys are entered.
}
// TODO write to Excel each entry in the map (you don't need to check for unique keys)

请注意,在映射完成后,将完成对Excel的写入。这是最好的方法;或者至少比你在原始帖子中展示的要好。使用这种方法,您可以让数据结构简化您的过程(并且没有嵌套循环(。

更新

我忘了提到matchList.putIfAbsent(K, V)可以与Java8及更高版本配合使用。如果使用Java 7或更早版本(应尽快升级Java(,则必须执行以下操作:

String value = matchList.get(record[0]);
if (value == null) {
matchList.put(record[0], record[1]);
}

这是因为Map#get(K)返回null是找不到条目,或者映射允许为给定键输入空值。否则,它将返回以前的值。Java 8中引入的新方法会自动执行此检查。

最新更新