You are here:

Java/Compare two .CSV

Advertisement


Question
Hello,

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?

Answer
This 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.
  }
}

Java

All Answers


Answers by Expert:


Ask Experts

Volunteer


Artemus Harper

Expertise

I have a Masters in computer science. I can answer questions on core J2SE, swing and graphics. Please no questions about JSP or J2ME.

Experience

I have experience in Core Java, good background in Java swing/gui, some experience with JNI, Java reflection. Some experience in bio-informatics. Basics in c++ and c#

Organizations
Washington State University

Education/Credentials
MS in Computer Science from Washington State University and a BS in Mathematics and Computer Science from Central Washington University.

©2012 About.com, a part of The New York Times Company. All rights reserved.