读取CSV文件并将其存储在HASHMAP中

时间:2018-08-02 09:46:41

标签: java csv apache-commons opencsv

我正在尝试读取CSV文件,并将键值对保留在 HASHMAP CSV Apache Commons 均被考虑

HashMap<String, Student>

其中的键将在字符串中存储学生名册编号,而学生在其 POJO 中具有相应的数据,例如名册编号,学生姓名,课程

现在在CSV中,我具有以下标题:年(加入数据),卷名,学生姓名,课程

两种方式:

  1. 要检查标题,因为我已经知道我想要的列值,但需要检查列号

  2. 没有标题,我已经特别知道标题在哪个列号上 被放置,因此我已经将其删除了

首先我尝试了没有标题

Map<String, Student> map =new HashMap<String, Student>(); 
        Student student=new Student();
     try {

            // Create an object of filereader
            // class with CSV file as a parameter.
            FileReader filereader = new FileReader("C:\\Users\\hpadmin\\ExcelDocuments\\1_Roll_spec.csv");

            // create csvReader object passing
            // file reader as a parameter
            CSVReader csvReader = new CSVReader(filereader,',', '\'', 1);
            String[] nextRecord;

            // we are going to read data line by line
            while ((nextRecord = csvReader.readNext()) != null) {

                student.setRoll_No(nextRecord[1]);
                student.setStudentName(nextRecord[2]);
                map.put(nextRecord[1], student);
                nextRecord=null;
            }

            Set<Map.Entry<String, Student>> set = map.entrySet();

            for (Map.Entry<String, Student> me : set) {
                  System.out.println(" Roll No : "+ me.getValue().getRoll_No()+" Student Name :"+me.getValue().getStudentName());

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

但是我只有最后一个地址也等于记录数,我也不知道与标头有关,而是根据标头名称读取

0 个答案:

没有答案