将 CSV 文件读入 java Object

Read CSV file into java Object

我正在尝试将 CSV 文件内容读入 java object。我找到了解释两种读取 CSV 方法的在线资源,即 BufferReader/OpenCSV。但是它们中的大多数都是关于按行读取的(我的意思是将所有行数据作为一个数据),我的实现的问题是我的 CSV 中的数据是按列显示的,如下所示:

更新:

Name,A,B,C,D
JoinDate,1/1/2019,1/1/2018,06/01/2018,1/1/2019
Math_Marks,80,50,65,55
Social_Marks,80,50,86,95
Science_Marks,70,50,59,85
FirstLang_Marks,60,50,98,45
SecondLang_Marks,90,97,50

如您所见,标记值不是强制性的,在上面的文件中,D 没有列出 "SecondLang_Marks"

的标记

我的 class object 如下:

public class StudentVO {

private String name;
private Calendar joinDate;
private int math_Marks;
private int social_Marks;
private int science_Marks;
private int FirstLang_Marks;
private int secondLang_Marks;

// All get and set methods for class variables    
}

任何人都可以帮助我根据垂直 headers 垂直阅读上面的 csv 并将值加载到 class object.

如果可能,您能否给出使用 BufferReader 和 OpenCSV 的示例。

谢谢

据我所知,您只能按行从文件中读取数据,没有任何垂直读取文件的机制。但是我有一个解决方案,读取整个文件,您可以创建一个学生数组并使用默认构造函数对其进行初始化,然后在逐行向下读取的同时设置数据。

try {
        BufferedReader reader = new BufferedReader(new FileReader("file.csv"));

        // Reading first line..
        String[] names = reader.readLine().split(",");
        // Execpt 'names' there are total 4 students, A,B,C,D.
        int totalStudents = names.length - 1;
        StudentVO[] array = new StudentVO[totalStudents];
        // Initialize all students with default constructor.
        for(int i = 0; i < array.length; i++) {
            array[i] = new StudentVO();
        }

        //////////////
        // Start reading other data and setting up on objects..
        // Line 2..
        String[] joinDates = reader.readLine().split(",");
        // i = 0 gives us the string 'joinDates' which is in the first column.
        // so we have to skip it and start it from i = 1
        for(int i = 1; i < joinDates.length; i++) {
            // setting the objects data..
            array[i - 1].setJoinDate(joinDates[i]); 
        }

        // And keep on doing this until SecondLang_Marks..

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

根据我的说法,这是此解决方案的最佳方法。