下面是我的工作到目前为止我已经使用了2个csv文件并制作了2个不同的数组代表2个csv文件数据现在我想要做的是我想比较那个2个数组并打印相同的值或元素这两个阵列都是一样的,这是我遇到困难的地方
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class CSVReaderw {
public static void main(String[] args) {
String csvFile1 = "/Users/Documents/AD.csv";
String csvFile2 = "/Users/Desktop/database.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
String[] ad = null;
String[] database = null;
try {
br = new BufferedReader(new FileReader(csvFile1));
while ((line = br.readLine()) != null) {
// use comma as separator
ad = line.split(cvsSplitBy);
//System.out.println("AD [id= " + ad[2] +"]");
}
System.out.println("second file result starts here");
br = new BufferedReader(new FileReader(csvFile2));
while ((line = br.readLine()) != null) {
database = line.split(cvsSplitBy);
//System.out.println("ID =" + database[0]);
}
List<String> commonListLambda = Arrays.stream(database)
.filter(x -> Arrays.asList(ad).contains(x))
.collect(Collectors.toList());
System.out.println(commonListLambda);
// List<String> commonList = new ArrayList<>();
//
// for(int i = 0; i < ad.length; i++){
// if(Arrays.asList(databse).contains(ad[i]))
// commonList.add(ad[i]);
// }
//
// System.out.println(commonList);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
编辑: 请参阅我们在此处指出的更新代码
答案 0 :(得分:1)
问题是你要重新编写你的数组,而不是向它添加数据。
while ((line = br.readLine()) != null) {
database = line.split(cvsSplitBy);
一般逻辑错误,您需要将一个文件中的单元格与其他文件中的单元格进行比较。
请参阅建议的解决方案,我试图使代码不言自明。
public class CSVReaderw {
public static void main(String[] args) {
String adDotCsv = "/Users/Documents/AD.csv";
String databaseDotCsv = "/Users/Desktop/database.csv";
String line = "";
String cvsSplitBy = ",";
BufferedReader br = null;
List<String> databaseList = new ArrayList<>();
List<String[]> adList = new ArrayList<>();
try {
br = new BufferedReader(new FileReader(databaseDotCsv));
while ((line = br.readLine()) != null) {
databaseList.addAll(Arrays.asList(line.split(cvsSplitBy)));
}
br = new BufferedReader(new FileReader(adDotCsv));
line = "";
while ((line = br.readLine()) != null) {
adList.add(line.split(cvsSplitBy));
}
List<String[]> commonList = new ArrayList<>();
String cellCInAdFile = null;
for (String[] rowInAdList : adList) {
cellCInAdFile = Arrays.toString(rowInAdList).split(",")[2].trim();
for (String cellAinDatabaseFile : databaseList) {
if (cellCInAdFile.equals(cellAinDatabaseFile.trim())) {
commonList.add(rowInAdList);
}
}
}
for (String[] rowInCommonList : commonList) {
System.out.println(Arrays.asList(rowInCommonList));
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}