1

Tengo los siguientes archivos .csv leídos en Java.

El primer archivo csv contiene la siguiente información (semestres):

3,Primavera
5,Primavera
5,Verano
12,Primavera
10,Verano
22,Otono

El segundo archivo csv contiene (carreras):

3,bachiller en ciencias    
5,bachiller en artes    
12,artes culinarias    
15,maestria en artes    
22,maestria en ciencias

Sin embargo, la salida en terminal (no en otro CSV) debería ser así:

(salida)

3,bachiller en ciencias,Primavera
5,bachiller en artes,Primavera,Verano
12,artes culinarias,Primavera
15,maestria en artes
22,maestria en ciencias,Otono

¿Comó puedo hacer para que la salida se cumpla, es decir, para que se comparen los códigos de las carreras con los códigos de carreras en semestres, y así, agregar al final en que otros semestres son ofrecidas, tal como muestra el ejemplo?

4

1 respuesta 1

2

Hay una librería que te permite leer fácilmente archivos CSV. Se trata de Univocity Parsers

Por ejemplo, para leer un CSV:

CsvParserSettings settings = new CsvParserSettings();
    //the file used in the example uses '\n' as the line separator sequence.
    //the line separator sequence is defined here to ensure systems such as MacOS and Windows
    //are able to process this file correctly (MacOS uses '\r'; and Windows uses '\r\n').
    settings.getFormat().setLineSeparator("\n");

    // creates a CSV parser
    CsvParser parser = new CsvParser(settings);

    // parses all rows in one go.
    List<String[]> allRows = parser.parseAll(getReader("/examples/example.csv"));

Para hacer lo que planteas en la pregunta, bastaría con leer un archivo, archivarlo en un Map, y luego leer el segundo, archivarlo en otro Map o en una lista y luego combinarlos.


Te dejo un ejemplo que podría servirte, aunque quizá tengas que darle algunos retoques:

Primero leemos uno de los archivos CSV y generamos un Map:

public static void main(String... args) {
    //First we parse one file (ideally the smaller one)
    CsvParserSettings settings = new CsvParserSettings();
    //here we tell the parser to read the CSV headers
    settings.setHeaderExtractionEnabled(true);

    CsvParser parser = new CsvParser(settings);

    //Parse all data into a list.
    List<String[]> records = parser.parseAll(new File("/path/to/csv1.csv"));
    //Convert that list into a map. The first column of this input will produce the keys.
    Map<String, String[]> mapOfRecords = toMap(records);

    //this where the magic happens.
    processFile(new File("/path/to/csv2.csv"), new File("/path/to/diff.csv"), mapOfRecords);

}

Este es el código para generar un Map desde la lista de registros:

    /* Converts a list of records to a map. Uses element at index 0 as the key */
private static Map<String, String[]> toMap(List<String[]> records) {
    HashMap<String, String[]> map = new HashMap<String, String[]>();
    for (String[] row : records) {
        //column 0 will always have an ID.
        map.put(row[0], row);
    }
    return map;
}

Con el mapa de registros, podemos procesar el segundo archivo CSV y generar otro Map con los datos actualizados:

Nota: En la pregunta en inglés se trataba de comparar dos archivos, quizá para tu caso en esta etapa haya que agregar el dato que falta del segundo archivo. El ejemplo es adaptable.

private static void processFile(final File input, final File output, final Map<String, String[]> mapOfExistingRecords) {
    //configures a new parser again
    CsvParserSettings settings = new CsvParserSettings();
    settings.setHeaderExtractionEnabled(true);

    //All parsed rows will be submitted to the following Processor. This way you won't have to store all rows in memory.
    settings.setProcessor(new RowProcessor() {
        //will write the changed rows to another file
        CsvWriter writer;

        @Override
        public void processStarted(ParsingContext context) {
            CsvWriterSettings settings = new CsvWriterSettings(); //configure at till
            writer = new CsvWriter(output, settings);
        }

        @Override
        public void rowProcessed(String[] row, ParsingContext context) {
            // Incoming rows from will have the ID as index 0.
            // If the map contains the ID, we'll get a row
            String[] existingRow = mapOfExistingRecords.get(row[0]);

            if (!Arrays.equals(row, existingRow)) {
                writer.writeRow(row);
            }
        }

        @Override
        public void processEnded(ParsingContext context) {
            writer.close();
        }
    });

    CsvParser parser = new CsvParser(settings);
    //the parse() method will submit all rows to the RowProcessor defined above. All differences will be
    //written to the output file.
    parser.parse(input);
}

Fuente: Stackoverlow en inglés: Java compare two csv files

2
  • Sugieres, entonces, la creacion de un archivo adicional, los dos originales mas uno nuevo. La idea es imprimir en consola la muestra.
    – Mr. Munoz
    el 17 mar. 2017 a las 3:28
  • @Mr.Munoz Es un código de ejemplo. Si no necesitas el archivo adicional no tienes que crearlo, solamente imprimes con System.out.println el contenido del mapa en el que has unido los valores. Imprimir o guardar es algo adicional que puedes hacer o no de acuerdo a tus requerimientos.
    – A. Cedano
    el 17 mar. 2017 a las 3:35

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.