AllExperts > Java 
Search      
Java
Volunteer
Answers to thousands of questions
 Home · More Java Questions · Answer Library  · Encyclopedia ·
More Java Answers
Question Library

Ask a question about Java
Volunteer
Experts of the Month
Expert Login

Awards

About Us
Tell friends
Link to Us
Disclaimer

 
 
 
 
About Artemus Harper
Expertise
I have a BS in computer science and am working towards a Masters degree.

Experience
I have experience in Core Java, good background in Java swing/gui, some experience with JNI, Java reflection. knowledge of Java bytecode and annotations. Basics in c++ and c#

Education/Credentials
BS in Computer Science at Central Washington University

 
   

You are here:  Experts > Computing/Technology > Focus on Java > Java > Compare two .CSV

Java - Compare two .CSV


Expert: Artemus Harper - 11/7/2009

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

Add to this Answer   Ask a Question


 
User Agreement | Privacy Policy | Kids' Privacy Policy | Help
Copyright  © 2008 About, Inc. AllExperts, AllExperts.com, and About.com are registered trademarks of About, Inc. All rights reserved.