首页 > 解决方案 > 读取 CSV 文件并存储在 HASHMAP 中

问题描述

我正在尝试读取 CSV 文件并将键值对保存在HASHMAP中CSVApache 公共 都被考虑

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();
        }

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

标签: javacsvapache-commonsopencsv

解决方案


推荐阅读