java comparing-two-csv-files-in-java

java comparing-two-csv-files-in-java

To compare two CSV (Comma Separated Values) files in Java, you can follow these steps:

  1. Read the contents of both CSV files into memory. You can use a library like Apache Commons CSV or OpenCSV to parse the CSV files and read the data into memory.

  2. Iterate through the rows of both files and compare the values of each column. You can use a for loop or an iterator to go through the rows of the files, and use the equals method to compare the values of each column.

  3. If you find a difference between the two files, you can log the difference and continue comparing the rest of the file.

  4. When you reach the end of both files, you can print a summary of the comparison, indicating whether the files are the same or not.

Here is an example of how you can compare two CSV files in Java:

refer‮ttual:ot ‬uri.com
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Main {
  public static void main(String[] args) throws IOException {
    // Read the contents of the first CSV file
    BufferedReader reader1 = new BufferedReader(new FileReader("file1.csv"));
    CSVParser parser1 = new CSVParser(reader1, CSVFormat.DEFAULT);
    List<CSVRecord> records1 = parser1.getRecords();

    // Read the contents of the second CSV file
    BufferedReader reader2 = new BufferedReader(new FileReader("file2.csv"));
    CSVParser parser2 = new CSVParser(reader2, CSVFormat.DEFAULT);
    List<CSVRecord> records2 = parser2.getRecords();

    // Compare the contents of both files
    boolean filesAreEqual = true;
    int numRows = Math.max(records1.size(), records2.size());
    for (int i = 0; i < numRows; i++) {
      CSVRecord record1 = i < records1.size() ? records1.get(i) : null;
      CSVRecord record2 = i < records2.size() ? records2.get(i) : null;

      // Check if the records have the same number of columns
      if (record1 != null && record2 != null && record1.size() != record2.size()) {
        System.out.println("Row " + (i + 1) + ": different number of columns");
        filesAreEqual = false;
        continue;
      }

      // Compare the values of each column
      int numColumns = Math.max(record1 != null ? record1.size() : 0, record2 != null ? record2.size() : 0);
      for (int j = 0; j < numColumns; j++) {
        String value1 = j < record1.size() ? record1.get(j) : "";
        String value2 = j < record2.size() ? record2.get(j) : "";

        if (!value1.equals(value2)) {
          System.out.println("Row " + (j) + " is not same ");
        }
Created Time:2017-11-03 00:14:51  Author:lautturi