I'm attempting to read in a CSV file with various data types.
A row of the sheet would be like below:
Single, Monthly, Accelerated, John, Smith, 08/15/1951, Yes
I then need to assign each field to a variable name, preform some calculations, print an output and then move onto the next line in the excel sheet
Up until now, I've been using the below
ArrayList lines = new ArrayList<>();
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
But this creates an array with each slot containing a long string with the text (including comma) of the corresponding excel row.
This seems inefficient and impractical as i then have to traverse each slot/string to extract the values.
Once I have the methodology, I wont have any issue writing the code but i don't know the best way to go about it
Is it better to read each cell separately and assign to a variable ?
Or is it better to read in a file once and traverse it afterwards?
Perhaps there is a more efficient way to do this task
Edit : I also though of attempting to read in the entire CSV file as a 2D array, but the different data types could be an issue..?
解决方案
You can try something similar to this. Use StringTokenizer to split the line by comma and add those elements to another List as strings in each iteration.
ArrayList> lines = new ArrayList<>();
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = reader.readLine()) != null) {
ArrayList tokens = new ArrayList<>();
StringTokenizer st = new StringTokenizer(line, ",");
while (st2.hasMoreElements()) {
tokens.add(st2.nextElement());
}
lines.add(tokens);
}
}
Now you can use proper casts to convert them to types you want. For example, to get the date,
DateFormat format = new SimpleDateFormat("mm/dd/yyyy", Locale.ENGLISH);
String dateString = lines.get(0).get(5);
Date date = format.parse(dateString);