Read the CSV file and save it in a 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 in a linked list that I have already configured.

My question is: what would be the easiest way? I do not publish specifics, as I am just looking for general (but simple) ideas; I would like to find out for myself. We have not done much more advanced file I / O than FileReader / FileWriter. The only way I could do this is to use Scanner to import each row, and then use String.split() to split everything into an array, then go through the array and manually pull everything out / convert to the correct format (since they will all be strings), and then paste everything at once into a linked list. It looks like an incredibly roundabout way.

Is there an easier way to accomplish this?

+4
source share
3 answers

Unfortunately, you have already found the simplest solution.

In general, the general presentation of data is very inconvenient in Java because it is statically typed. Part of the CSV, XML, and other data serialization methods are that they are self-documenting in terms of the structure of the data being defined. In the case of Java, this does not work too well, because the structure must either be predefined (via the class) or read into the structure, so it is almost useless (for example, a list map or key-> where everything remains a line).

This is not hatred of Java hatred, I simply point out that making this specific work easy and intuitive is fundamentally incompatible with the functions of the Java kernel. In a dynamically typed language such as Python, such things are much simpler (and in particular in Python, they are almost trivial due to the presence of the main csv module), because you can drop any data into the object and it will adapt to match, Java should Know in advance what will happen, which leads to uncomfortable verbosity that you discover.

+2
source

There is a better solution without reinventing the wheel: Add this opencsv library If you use Maven, you can put this code in your pom net.sf.opencsv opencsv 2.3 file

And the library documentation very well explains how to use 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); 

Hope this helps you.

+5
source

StringUtils from the Spring Framework has some features for this. But I would say that it does not matter and introduces an unnecessary dependency.

Stick to your idea.

+1
source

Source: https://habr.com/ru/post/1445138/


All Articles