Java CSV file splitting

Asked

Viewed 816 times

2

I have a problem very grade in the use of CSV file in Java, I’m doing a job and for days I can not have a functional idea for this part, next, I have to create a routine that receives a csv containing the data of more than one class filled in as follows:

class;id;nome;celular;email
Aluno;7;Alguem;21 12345678;[email protected]
Aluno;2;Fulano;31 4553;
Aluno;5;Sr. Beltrano;;[email protected]

class;nome;id
Turma;turma1;3
Turma;turma2;26

The first line of each group contains the data that this class has, the first is the class name and the others are its attributes, I have to use this data to fill these classes, I’m just saying this to understand the history behind. I need to somehow read and separate these groups and pass them to a method that will fill this (I haven’t done it yet), I’m trying to read the file as follows:

List<String> lines = Files.readAllLines(p, c);

Where P is the path and c is the Charset.I can walk through the lists manipualr and such, I’ve tried a lot and as I’m new in language there are sure practical methods to do this that I haven’t found anywhere.

  • has only one separate row the file?

  • exact, and may have more than one classes in the file, so between each class is an empty row

  • 2

    Possible duplicate of How to read CSV files in Java

  • I saw this post there, only that it simply wants to separate using the split, it’s a little different my question.

  • If the order is student a line separating and then the class advise you to do the following. Read the file as a normal string. Separate it using the split and then go through the generated array, so Oce knows that the first is the student and then the class and then the student and then the class. Thus successively.

  • The blank line only separates two different classes like this one above, where this "class;id;name;cellular;email" is the order that will be arranged the data below, only when the blank line appears is a new class started, "class;name;id"

  • If I were not due two answers (which are still in writing), I would answer this with the greatest pleasure. But I warn you: heterogeneous data in the same CSV is not auspicious

  • I think I got this job just to learn how to use files. The second part of filling the Generics I believe I know how to do, this separation of data that is complicated.

  • But I don’t see how your question is any different. Iterate each of the lines you read and use split. If you look at the size of the resulting array, you can even tell which line it is on, so you can act differently. Personally this structure does not seem to me the best. If it has different classes would be different files, each with its structure.

Show 4 more comments

1 answer

2

Hi, first try to standardize your CSV, set the name of the columns and once set try not to move it any more like changing the positions of the columns so it will be easier to manipulate on the Java side, for example:

class;id;name;cellular;email
Student;7;Anyone;21 12345678;[email protected]
Student;2;So-and-so;31 4553;
Student;5;Mr. Beltrano;;[email protected]

What I see in my head is just why you decided to use in the name of the class in a column, in my opinion this is bad practice, try to find some alternative.

To manipulate in Java you can create a POJO class that will only have the name of the variables and their respective getters and setters:

/**
 * Dados dos valores que contém no CSV
 */
public class Pojo {

    private String nomeDaClasse;

    private Integer oId;

    private String nome;

    private String numeroCelular;

    private String email;

    /**
     * @return the nomeDaClasse
     */
    public String getNomeDaClasse() {
        return nomeDaClasse;
    }

    /**
     * @param nomeDaClasse the nomeDaClasse to set
     */
    public void setNomeDaClasse(String nomeDaClasse) {
        this.nomeDaClasse = nomeDaClasse;
    }

    /**
     * @return the oId
     */
    public Integer getoId() {
        return oId;
    }

    /**
     * @param oId the oId to set
     */
    public void setoId(Integer oId) {
        this.oId = oId;
    }

    /**
     * @return the nome
     */
    public String getNome() {
        return nome;
    }

    /**
     * @param nome the nome to set
     */
    public void setNome(String nome) {
        this.nome = nome;
    }

    /**
     * @return the numeroCelular
     */
    public String getNumeroCelular() {
        return numeroCelular;
    }

    /**
     * @param numeroCelular the numeroCelular to set
     */
    public void setNumeroCelular(String numeroCelular) {
        this.numeroCelular = numeroCelular;
    }

    /**
     * @return the email
     */
    public String getEmail() {
        return email;
    }

    /**
     * @param email the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }

}

Now it’s time to read the CSV file, read by line, divide the value by semicolon and add the values in the Pojo class array

/**
     * 
     * @param caminhoArquivo o caminho do arquivo que contém seu CSV
     * @param separador o separador do seu CSV, no caso ponto e virgula
     * @param temHeader se tem header, ou seja, o nome das colunas, então o código pula essa parte
     * @return os dados do CSV em um array
     * @throws IOException erro ao ler o arquivo
     */
    public static ArrayList<Pojo> lerCSV(String caminhoArquivo, String separador, boolean temHeader) throws IOException {
        ArrayList<Pojo> pojos = new ArrayList<>();

        try (BufferedReader br = new BufferedReader(new FileReader(caminhoArquivo))) {
            String linha;
            boolean eCabecalho = temHeader;
            while ((linha = br.readLine()) != null) {
                if (eCabecalho || linha.trim().isEmpty()) {
                    eCabecalho = false;
                    continue;
                }
                String[] colunas = linha.split(separador, 5); //Presumo que seu CSV tenha 5 colunas
                if (colunas.length != 5) {
                    System.out.println("O CSV tem mais ou menos de 5 colunas!");
                    continue;
                }
                try {
                    String nomeDaClasse = colunas[0].trim();
                    Integer oId = Integer.parseInt(colunas[1].trim());
                    String nome = colunas[2].trim();
                    String numeroCelular = colunas[3].trim();
                    String email = colunas[4].trim();
                    System.out.println(nomeDaClasse + ";" + oId + ";" + nome + ";" + numeroCelular + ";" + email);
                    Pojo pojo = new Pojo(); 
                    pojo.setNomeDaClasse(nomeDaClasse);
                    pojo.setNome(nome);
                    pojo.setEmail(email);
                    pojo.setNumeroCelular(numeroCelular);
                    pojo.setoId(oId);
                    pojos.add(pojo);
                } catch (Exception ex) {
                    System.out.println("Deu algum problema!\n " + ex);
                }

            }
        }

        return pojos;
    }

Browser other questions tagged

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