Subtract one CSV from another in Java

Use the following code to subtract a CSV file from Another CSV file.

How to use the following program
File to subtract: file1.csv (input)
File from which to subtract: file2.csv (input)
New file: p3lang.csv (output)


import java.util.ArrayList;

/* file1 - file2 = file3*/
public class CompareCSV {
    public static void main(String args[]) throws FileNotFoundException, IOException
        String path="D:\\csv\\";
        String file1="file1.csv";
        String file2="file2.csv";
        String file3="p3lang.csv";
        ArrayList al1=new ArrayList();
        ArrayList al2=new ArrayList();
        //ArrayList al3=new ArrayList();
        BufferedReader CSVFile1 = new BufferedReader(new FileReader(path+file1));
        String dataRow1 = CSVFile1.readLine();
        while (dataRow1 != null)
            String[] dataArray1 = dataRow1.split(",");
            for (String item1:dataArray1)
            dataRow1 = CSVFile1.readLine(); // Read next line of data.
        BufferedReader CSVFile2 = new BufferedReader(new FileReader(path+file2));
        String dataRow2 = CSVFile2.readLine();
        while (dataRow2 != null)
            String[] dataArray2 = dataRow2.split(",");
            for (String item2:dataArray2)
            dataRow2 = CSVFile2.readLine(); // Read next line of data.
         for(String bs:al2)
         int size=al1.size();
                FileWriter writer=new FileWriter(path+file3);
            catch(IOException e)
  • Rohin

    Hey Abhishek,

    You must provide the complete working program (to download) of the above post.

    Thanks in advance!

    • Hi Rohin Saini,

      There is nothing complex that it requires a download link. Just copy it and it will work for you.
      Please let me know if you further face any problem. Happy to help

  • HelpPlease

    I get a problem on line 45 about incompatible type error, with the String.

    • Hi,
      The post has been updated. Thank u for identifying the error.
      The following lines are updated

              ArrayList al1=new ArrayList();
              ArrayList al2=new ArrayList();
  • ashu

    found : java.lang.object
    required: java.lang.String

    for(String bs:al2)

    note: uses unchecked or unsafe operations.
    note: Recompile with -xlint: unchecked for details.

    this is the error i am getting while compiling this code

    • Hi Ashu,

      It is giving you the warning.
      I think you are using CMD to compile the program.
      use command:

      javac -Xlint

      It will show you the warnings.
      I have updated the 12th & 13th line again to resolve this.
      Thanx :)

%d bloggers like this: