将CSV文件读入Java对象

时间:2019-01-22 19:23:37

标签: java opencsv

我正在尝试将CS​​V文件内容读取到java对象中。我发现在线资源解释了读取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”中没有列出标记

我的班级对象在下面:

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    
}

任何人都可以帮助我根据垂直标题垂直读取上述csv并将值加载到类对象中。

如果可以,请同时使用BufferReader和OpenCSV给出两个示例。

谢谢

1 个答案:

答案 0 :(得分:2)

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

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

根据我的看法,这是解决此问题的最佳方法。