Problem writing to a CSV file with OpenCSV

0

I want to write the data of each object Persona saved in a ArrayList of type Persona in a CSV file using the library OpenCSV , but the writing that I get in the file csv is incorrect.

Just write the data of the first element in the list and do not jump to the next line.

clase Persona:

  public class Persona {

        String Nombre;
        String Apellido;
        String Intereses;
        String Descripcion;

        public Persona(String Nombre,String Apellido,String Intereses,String Descripcion)
        {        
                this.Nombre = Nombre;
                this.Apellido= Apellido;
                this.Intereses = Intereses;
                this.Descripcion = Descripcion;

        }

        public String getNombre(){
            return Nombre;
        }

        public String getApellido(){
            return Apellido;
        }
        public String geIntereses(){
            return Intereses;
        }

        public String getDescripcion(){
            return Descripcion;
        }
    }

main class:

    import java.util.ArrayList;      
    import java.io.IOException;
    import java.io.FileWriter;

    import com.opencsv.*;

public class main{

    public static String[] getDatosPersona(Persona persona) {

        String nombre = persona.getNombre();
        String Apellido = persona.getApellido();
        String intereses = persona.geIntereses();
        String descripcion = persona.getDescripcion();

        String []  datos = {nombre,Apellido,intereses,descripcion};

        return datos;

    }

     public static void main(String [] args) throws IOException{

         ArrayList<Persona> personas = new ArrayList();

         Persona persona1 = new Persona("jose","delgado","sus intereses","su descripción");         
         Persona persona2 = new Persona("martin","rosero","sus intereses","su descripción");
         Persona persona3 = new Persona("pedro","cruz","sus intereses","su descripción");


         personas.add(persona1);
         personas.add(persona2);
         personas.add(persona3);



         CSVWriter  csvOutput = new CSVWriter (new FileWriter("C:\Users\BryanPC\Desktop\otrofile.txt",true));

         for(Persona p:personas){

         csvOutput.writeNext(getDatosPersona(p));


        }
         csvOutput.close();

     }
}

output:

"jose","delgado","sus intereses","su descripción""jose","delgado","sus intereses","su descripción""jose","delgado","sus intereses","su descripción"

expected output:

"jose","delgado","sus intereses","su descripción"
"martin","rosero","sus intereses","su descripción"
"pedro","cruz","sus intereses","su descripción"
    
asked by Bryan Romero 16.05.2016 в 19:23
source

1 answer

1

You can also specify the new line character to use in OpenCSV. That is:

Writer writer = FileWriter("C:\Users\BryanPC\Desktop\otrofile.txt", true);
CSVWriter csvOutput = new CSVWriter(writer, ',', '"', "\r\n");
    
answered by 17.05.2016 / 09:13
source