Home > Back-end >  Compare two CSV files on multiple column and create new CSV file in Java
Compare two CSV files on multiple column and create new CSV file in Java

Time:08-12

I have two csv files File 1:

ID,NAME
1,FOO
2,BAR
3,XYZ

File 2:

ID,NAME,DOB
3,XYZ,02/03/1999
4,BAR,01/01/1995
1,FOO,01/01/1996

How can I select rows from CSV File 2 which has columns ID,NAME value matched in File 1 in java language.

Expected Result:

ID,NAME,DOB
3,XYZ,02/03/1999
1,FOO,01/01/1996

CodePudding user response:

Basically you want to perform Vlookup operation .

You can get desired outcome by using Apache POI library. This library provides set of methods to perform Vlookup.

You can refer to the below resources for detailed understanding. https://poi.apache.org/apidocs/dev/org/apache/poi/ss/formula/functions/Vlookup.html

CodePudding user response:

There are a lot of API's that support functions like comparing .csv files. However, Java also has its own ways to do this.


I'll explain it step by step:

  • First, you should read the two files into the program. java.io provides some classes with this functionality.

  • Then, after the content of both files is stored in an appropriate data structure, you can compare them.

  • You can then simply store the matching lines in another data structure and return them.

  • Last but not least, you also have to write to a new or already existing file using classes from java.io.


Here is a method to read in files:

  public ArrayList<String> readInFile(String absoluteFilePath) {

        BufferedReader reader = null;
        ArrayList<String> csvContent = new ArrayList<>();
        String currentLine;
        
        try {
            reader = new BufferedReader(new FileReader(absoluteFilePath));
            
            while((currentLine = reader.readLine()) != null) {
                csvContent.add(currentLine);
            }
            reader.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return csvContent;
    }

The method uses a BufferedReader to read the file and adds it line by line to the ArrayList


Writing to a .csv file is just as easy as reading from one. You just have to decide whether you want to write to an existing file or to a file that already exists.

Here is a method to write into files:

  public void writeToFile(ArrayList<String> csvContent, String absoluteFilePath) {

        BufferedWriter writer = null;

        try {
            writer = new BufferedWriter(new FileWriter(absoluteFilePath));

            for (int i = 0; i < csvContent.size(); i  ) {
                writer.write(csvContent.get(i)   "\n");
            }

            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

This method uses a BufferedWriter to either create a file at the given path or overwrite an existing one and writes the contents of the ArrayList into the file.

Good luck!

  •  Tags:  
  • java
  • Related