1
UserName,Password
User1,Pwd1
User2,Pwd1
User3,Pwd3

Assume there is a csv file with user names and passwords as I've mentioned above. I need to read the csv file and store data in a hash map using open CSV; keys should be Username and password and values should be user1, pwd1...etc.

I'm able to read data from the csv file but not able to get column header (UseName , Password) as keys and data as values to store in hash map. Please see the below code that I tried to do so. I need to know how to get cell values from CSV file (like in excel sheet)

@Test
public void dpmethod()throws Exception{
    String csvfile = "C:\\Users....TestData\\LoginData.csv";
    CSVReader  reader= new CSVReader(new FileReader(csvfile));

    try {
        String[] cell; 
        Map<Object, Object> datamap = new HashMap<Object,Object>();  
        while((cell =reader.readNext())!=null) {
            for( int i=0; i<cell.length;i++ ) {
                System.out.println(cell[i]);
                //datamap.put(Key, value );
            }

         }
       }
       catch(NullPointerException e) {
           e.printStackTrace();
       }
}

1 Answer 1

1

You can use Apache's Common CSV library:

enter image description here

The method getHeaderMap retrieves the header names.

Maven link: https://mvnrepository.com/artifact/org.apache.commons/commons-csv/1.5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.