Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a .csv file and store to linked list in Java

I have a simple .csv file with five fields: firstName (string), lastName (string), age (int), gender (char), and priority (int). I need to read this file into a linked list that I already have set up.

My question is this: What would be the simplest way to go about this? I'm not posting specifics, as I'm just looking for general (but simple) ideas; I'd like to figure it out myself. We have not done much more advanced with file I/O than FileReader / FileWriter. The only way I can think of to accomplish this would be to use Scanner to import each line, then use String.split() to split everything into an array, then go through the array and manually pull everything / convert to the proper format (as they'll all be strings), then insert all at once into the linked list. This seems like an incredibly roundabout way, however.

Is there a simpler way I can accomplish this?

like image 391
vaindil Avatar asked Feb 19 '23 13:02

vaindil


2 Answers

There is an more effective solution, without re-invent the wheel: Add this library opencsv If you uses Maven, you can put this code in your pom file net.sf.opencsv opencsv 2.3

And in library documentation explains very well how to use it documentacion

ColumnPositionMappingStrategy strat = new ColumnPositionMappingStrategy();
strat.setType(YourOrderBean.class);
String[] columns = new String[] {"name", "orderNumber", "id"}; // the fields to bind do in your JavaBean
strat.setColumnMapping(columns);

CsvToBean csv = new CsvToBean();
List list = csv.parse(strat, yourReader);

I hope this help you.

like image 89
villanueva.ricardo Avatar answered Feb 26 '23 17:02

villanueva.ricardo


Unfortunately, you've already found about the easiest solution.

In general, generic data reading is very uncomfortable in Java because it's statically typed. Part of the point of CSV, XML, and other data serialization methods is that they're self-documenting in terms of the structure of the data being defined. In the case of Java, that doesn't work too well, because the structure has to either be predefined (via a class) or read into a structure so generic it's almost useless (like a list or key->value map where everything stays a string).

This isn't a Java hate-rant, I'm just pointing out that making this particular job easy and intuitive is fundamentally incompatible with Java's core language features. In a dynamically-typed language like Python, such things are much simpler (and in Python in particular, almost trivial because of the presence of the core csv module) because you can drop any sort of data into an object and it will adapt to fit. Java has to know ahead of time what's coming, which leads to the awkward verbosity that you've discovered.

like image 20
jfmatt Avatar answered Feb 26 '23 17:02

jfmatt