Search code examples
javacsvexport-to-csvopencsv

How to extract CSV columns with the specific header names and output to a new file?


If I have the file. The content inside looks like this:

ID,Name,Gender,Age,Enabled
1,Kevin,M,1,true
2,James,M,2,true
3,Jane,F,3,true
4,Jenny,F,4,true

Now I would like to extract the columns: ID, name, Gender and output them to a new file the following:

ID,Name,Age
1,Kevin,1
2,James,2
3,Jane,3
4,Jenny,4

I would like to extract the columns based on the header name, instead of the index number.

I would like to use OpenCSV.

How to achieve it?


Solution

  • There is no in-built method in CSVReader to read values using column names. But you can have a workaround as below for that by have another method created to get the correct column position.

        private int getPositionUsingName(String[] allColumnNames, String columnName) {
               return Arrays.asList(allColumnNames).indexOf(columnName);
        }
    

    So your method will be like:

    CSVReader csvReader = new CSVReader(new FileReader("inputFile.csv"));
    String [] allColumnNames;
    String [] nextLine;
    int idPosition;
    int namePosition;
    int agePosition;
    
    allColumnNames = csvReader.readNext();
    idPosition = getPositionUsingName(allColumnNames, "ID");
    namePosition = getPositionUsingName(allColumnNames, "Name");
    agePosition = getPositionUsingName(allColumnNames, "Age");
    
    while ((nextLine = csvReader.readNext()) != null) {
       System.out.println(nextLine[idPosition]+" "+nextLine[namePosition]+" "+nextLine[agePosition]);
    }