简体   繁体   中英

Read CSV file into java Object

I'm trying to read the CSV file content into a java object. I found online resources that explains the two ways to read CSV ie., BufferReader/OpenCSV. But most of them are about reading row wise(I mean all the row data as one), the problem with my implementation is my CSV has the data in column wise like below:

UPDATE:

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

As you see the marks value are not mandatory, in above file person D has no marks listed for "SecondLang_Marks"

and my class object is below:

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    
}

can anyone please help me to read the above csv vertically based on vertical headers and load the values into class object.

If possible can you please give both examples using BufferReader and OpenCSV.

Thanks

As far as i know, you can only read the data from file in row wise, there is not any mechanism to read the file vertically. But i have a solution for it, read the whole file, You can create a array of students and initialize it with default constructor and then set the data while reading downwards row wise.

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

This is the best way to do it for this solution according to the me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM