首页 > 解决方案 > 将 CSV 文件读入 java 对象

问题描述

我正在尝试将 CSV 文件内容读入 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 给出这两个示例。

谢谢

标签: javaopencsv

解决方案


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

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

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


推荐阅读