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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With