Java/Compare two .CSV
Expert: Artemus Harper - 11/7/2009
QuestionHello,
I Want to compare two .csv file and check..if the entries are equal
Well not exactly.equal..with 3% deviation.
It possible to use java Api
I thought of Using CSV reader and convert the object into array and check the entries..
Is it possible?
AnswerThis is pretty simple:
First create a Reader to read text in:
BufferedReader reader1 = new BufferedReader(new InputStreamReader(new FileInputStream("<your 1st file>"),"US-ASCII"));
BufferedReader reader2 = new BufferedReader(new InputStreamReader(new FileInputStream("<your 2nd file>"),"US-ASCII"));
Then iterate over each line:
while(true) {
String reader1Line = reader1.readLine();
String reader2Line = reader2.readLine();
if(reader1Line == null) {
if(reader2Line == null) {
//Success code
break;
}
else {
//Error file 2 has more lines than file 1
break;
}
}
else if(reader2Line == null && reader1Line != null) {
//Error file 1 has more lines than file 2
break;
}
...
}
Then, split each line into parts:
String[] line1Parts = reader1Line.split(",");
String[] line2Parts = reader2Line.split(",");
if(line1Parts.length != line2Parts.length)
//error different number of entries in the two rows
Next, iterate over each entry, checking to see if they are close.
for(int i = 0; i < line1Parts.length;i++) {
double entry1 = Double.parseDouble(line1Parts[i]);
double entry2 = Double.parseDouble(line2Parts[i]);
double average = (entry1 + entry2) / 2;
if(Math.abs((entry1 - entry2) / average) > 0.03) {
//Entries are too close.
}
}