How to read CSV files in Java

Asked

Viewed 28,007 times

11

I am developing a web application, where after the user uploads a CSV file, my java application needs to read this CSV. Preferably separate the data into fields, for example to add these into a database.

After some searches done on the web, some examples I understood, in the java code already brings the fields defined that the csv file has. Is it possible to scan the file even without knowing how many fields the line has? Because I can have files being sent to the application, with different fields.

  • Regardless of the solution adopted (there are 2 responses while writing), remember at all times, always validate the size of the array obtained from any input. So your code will be much more robust. Otherwise, if there is an unforeseen, such as an empty line at the end of the file (just to cite an example), the implementation will not break.

  • Thanks for the @utluiz tip, really helpful. Thank you.

4 answers

13


If you make a split of the lines and a map or even a list to store each position you will have no problem, then to each line just make an interacting loop for each element resulting from the split.

The example below is quite simplified, but it will serve to give you a north of how to proceed see, that I can get the last elements "unknowingly" how many there are on the line. Similarly, you will need to go to.length to iterate over the various elements of your csv.

csv file.

"1.0.0.0","1.0.0.255","16777216","16777471","AU","Australia"
"1.0.1.0","1.0.3.255","16777472","16778239","CN","China"
"1.0.4.0","1.0.7.255","16778240","16779263","AU","Australia"
"1.0.8.0","1.0.15.255","16779264","16781311","CN","China"
"1.0.16.0","1.0.31.255","16781312","16785407","JP","Japão"
"1.0.32.0","1.0.63.255","16785408","16793599","BR","Brasil"
"1.0.64.0","1.0.127.255","16793600","16809983","JP","Japão"
"1.0.128.0","1.0.255.255","16809984","16842751","DK","Dinamarca"

stack.Leiacvs.java

package stack;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class LeiaCVS {

  public static void main(String[] args) {

    LeiaCVS obj = new LeiaCVS();
    obj.run();

  }

  public void run() {

    String arquivoCSV = "arquivo.csv";
    BufferedReader br = null;
    String linha = "";
    String csvDivisor = ",";
    try {

        br = new BufferedReader(new FileReader(arquivoCSV));
        while ((linha = br.readLine()) != null) {

            String[] pais = linha.split(csvDivisor);

            System.out.println("País [code= " + pais[pais.length-2] 
                                 + " , name=" + pais[pais.length-1] + "]");

        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
  }

}
  • Thanks for the help @Kyllopardiun, I will adapt my code and test this implementation. Thank you.

9

Dude, you can just use Opencvs (http://opencsv.sourceforge.net/)

To adapt and use it just use the following code:

public class ParseCSV {
public static void main(String[] args) {
try {
  //csv file containing data
  String strFile = "C:\\Users\\rsaluja\\CMS_Evaluation\\Drupal_12_08_27.csv";
  CSVReader reader = new CSVReader(new FileReader(strFile));
  String [] nextLine;
  int lineNumber = 0;
  while ((nextLine = reader.readNext()) != null) {
    lineNumber++;
    System.out.println("Line # " + lineNumber);

    // nextLine[] is an array of values from the line
    System.out.println(nextLine[4] + "etc...");
  }
 }
}
}
  • 1

    Thank you, and can you tell me if using Opencvs is possible to read field by field from CSV? In this case I would make a repeat loop inside the while by scanning the nextLine[]?

  • In the past code, it reads line by line from your file that was loaded with Csvreader and puts in the array called nextLine...you can extract the information you want from them just by passing the position of the line you want (As at the end is nextLine[4]

6

The code below reads the records of a CSV file, using Opencsv.

In this example we get a List<String[]>.

    Reader reader = Files.newBufferedReader(Paths.get("nome-do-arquivo.csv"));
    CSVReader csvReader = new CSVReaderBuilder(reader)
                            .withSkipLines(1)//para o caso do CSV ter cabeçalho.
                            .build();

    List<String[]> linhas = csvReader.readAll();
    for (String[] linha : linhas)
        for (String[] coluna : linha)
            System.out.print(coluna + " # ");
        System.out.println();

Important: You need to add Opencsv as a dependency on your project. If you’re using Maven, just add:

<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>4.2</version>
</dependency>

Reference: https://dicasdejava.com.br/como-ler-arquivos-csv-em-java/

-3

Use python, it’s easier.

import pandas as pd

magica = pd.read_csv('ratings.csv')

magica or magica.head()

:)

  • 1

    If the question was asked in Java be kind and answer in Java. Language proselytism does not matter and is unnecessary.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.