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.
Answer from Rehan Javed on Stack OverflowReading CSV into objects
Java API to make an object from a CSV file - Stack Overflow
java - How to easily process CSV file to List<MyClass> - Stack Overflow
java - Reading from CSV file and create object - Stack Overflow
Videos
I'm pretty new to using Java as a developer. I have used java in the past, but only for my college CS classes which happened years and years ago (possibly Java v1.3?). I created a couple of examples of reading CSVs into objects using the opencsv and jackson libraries.
I'm posting these projects here to 1) get some feedback, 2) possibly help someone else who needs to read a CSV into their app.
-
opencsv-example
-
jackson-csv-example
Is there anything I can improve upon? If so, what? If either of these projects are helpful to you, let me know!
JSefa allow you to annotate Java classes that can be used in a serialization and de-serialization process. The tutorial demonstrates how this works with the CsvIOFactory class.
(From the tutorial) Annotating a bean is as simple as specifying the locations of the items in the list of values, and if necessary, you'll need to specify the conversion format:
@CsvDataType()
public class Person {
@CsvField(pos = 1)
String name;
@CsvField(pos = 2, format = "dd.MM.yyyy")
Date birthDate;
}
I prefer opencsv, it is ultra simple and very clean.
http://opencsv.sourceforge.net/
For example reading:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[0] + nextLine[1] + "etc...");
}
One of the simplest ways to read and serialize data is by using the Jackson library. It also has an extension for CSV, you can find the wiki here
Let's say you have a Pojo like this:
@JsonPropertyOrder({ "name", "surname", "shoesize", "gender" })
public class Person {
public String name;
public String surname;
public int shoesize;
public String gender;
}
And a CSV like this:
Tom,Tommy,32,m
Anna,Anny,27,f
Then reading it is done like so:
MappingIterator<Person> personIter = new CsvMapper().readerWithTypedSchemaFor(Person.class).readValues(csvFile);
List<Person> people = personIter.readAll();
This is simple enough for my taste, basically all you need to do is add the column order in your CSV file using the @JsonPropertyOrder annotation and then just read the file using the above 2 lines.
There are lot of good frameworks written in Java to parse a CSV file and form a List of Objects. OpenCSV, JSefa & jCSV are to name a few of them.
For your requirement, I believe jCSV suits the best. Below is the sample code from jCSV which you can make use of easily.
Reader reader = new FileReader("persons.csv");
CSVReader<Person> csvPersonReader = ...;
// read all entries at once
List<Person> persons = csvPersonReader.readAll();
// read each entry individually
Iterator<Person> it = csvPersonReader.iterator();
while (it.hasNext()) {
Person p = it.next();
// ...
}
Moreover, parsing a CSV file and converting it to a List isn't a big deal and it can be achieved without using any framework, as shown below.
br = new BufferedReader(new FileReader(csvFileToRead));
List<Person> personList = new ArrayList<>();
while ((line = br.readLine()) != null) {
// split on comma(',')
String[] personCsv = line.split(splitBy);
// create car object to store values
Person personObj = new Person();
// add values from csv to car object
personObj.setName(personCsv[0]);
personObj.setSurname(personCsv[1]);
personObj.setShoeSize(personCsv[2]);
personObj.setGender(personCsv[3]);
// adding car objects to a list
personList.add(personObj);
}
If the mapping of CSV columns to bean object is complex, repetitive or large in real case scenario, then it can be done easily by using DozerBeanMapper.
Hope this will help you.
Shishir