Read a csv file as an array in java

1

I've been experimenting with the com.opencsv and javacsv libraries but I always run into some pitfall with these packages: I can not write the first row, I can not read columns, among other problems. My question is: Is there a package that allows me to read and write a csv referencing row and column as if it were a spreadsheet or a matrix? I have seen something from the super CSV package but I also did not find the solution in this package.

    
asked by Julio Federico Buonfigli 28.03.2018 в 07:31
source

1 answer

0

You may not need a library.

You can load the contents of a text file using

Files.lines(path, StandardCharsets.UTF_8)

Then you can separate by the separation character and save in a list that you can then iterate:

String path = "C:\data\data.csv";
ArrayList<String[]> list = new ArrayList<>();
Files.lines(path, StandardCharsets.UTF_8).forEach(x->list.add(x.split(';')));

//Consigue el elemento en la columna 3 de la linea 23
String elementoBuscado = list.get(22)[2];

Arraylist may not be the most efficient collection for this depending on the size of the data and the available ram, but as an example it has to serve.

Note: Loading in arraylist with lambda requires at least Java 8, otherwise you will have to iterate.

    
answered by 28.03.2018 в 09:57