Convert CSV values to a HashMap key value pairs in JAVA

前端 未结 8 1023
刺人心
刺人心 2020-12-03 03:33

HI I have a csv called test.csv . I am trying to read the csv line by line and convert the values into a hash key value pairs . Here is the code :-



        
8条回答
  •  星月不相逢
    2020-12-03 04:35

    using openCSV would be one way to do it

    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    
    import au.com.bytecode.opencsv.CSVReader;
    
    public class CsvFileReader {
        public static void main(String[] args) {
    
            try {
                System.out.println("\n**** readLineByLineExample ****");
                String csvFilename = "C:/Users/hussain.a/Desktop/sample.csv";
                CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
                String[] col = null;
                while ((col = csvReader.readNext()) != null) 
                {
                    System.out.println(col[0] );
                    //System.out.println(col[0]);
                }
                csvReader.close();
            }
            catch(ArrayIndexOutOfBoundsException ae)
            {
                System.out.println(ae+" : error here");
            }catch (FileNotFoundException e) 
            {
                System.out.println("asd");
                e.printStackTrace();
            } catch (IOException e) {
                System.out.println("");
                e.printStackTrace();
            }
        }
    }
    

    the jar is available here

提交回复
热议问题