How to combine CSV files in Java

My first csv file looks like this: the header is included (the header is only included at the top after each entry):

NAME,SURNAME,AGE
Fred,Krueger,Unknown
.... n records

My second file might look like this:

NAME,MIDDLENAME,SURNAME,AGE
Jason,Noname,Scarry,16
.... n records with this header template

The merged file should look like this:

NAME,SURNAME,AGE,MIDDLENAME
Fred,Krueger,Unknown,
Jason,Scarry,16,Noname
....

In principle, if the headings do not match, all new headings for the headings (columns) should be added after the original heading and their values ​​in accordance with this order.

UPDATE:

Less CSVs have been made above, so I can illustrate what I want to achieve, in reality CSV files are generated one step before (merging) and can contain up to 100 columns

Does anyone know how I can do this? I would appreciate any help

+3
source share
3 answers

"" ( ) : , . csv csv . :

 public void convert(File output, File...input) {

   List<Record> records = new ArrayList<Record>();
   for (File file:input) {
     if (input.isThreeColumnFormat()) {
        records.addAll(ThreeColumnFormatParser.parse(file));
     } else {
        records.addAll(FourColumnFormatParser.parse(file));
     }
   }
   CsvWriter.write(output, records);
 }

, csv .

csv :

public class Record {
  Object id; // some sort of unique identifier
  Map<String, String> values; // all key/values of a single row
  public Record(Object id) {this.id=id;}
  public void put(String key, String value){
    values.put(key, value);
  }
  public void get(String key) {
    values.get(key);
  }
}

( ), , :

//...
List<Record> records = new ArrayList<Record>()

for (File file:getAllFiles()) {
  List<String> keys = getColumnsHeaders(file);
  KeyStore.addAll(keys);  // the store is a Set
  for (String line:file.getLines()) {
    String[] values = line.split(DELIMITER);
    Record record = new Record(file.getName()+i);  // as an example for id
    for (int i = 0; i < values.length; i++) {
      record.put(keys.get(i), values[i]);
    }
    records.add(record);
  }
}
// ...

, , ( null, ), csv .

+1

. , . , , .

, " " . . null, ( , ).

, , , .

+1

Try the following:

http://ondra.zizka.cz/stranky/programovani/ruzne/querying-transforming-csv-using-sql.texy

crunch input.csv output.csv "SELECT AVG(duration) AS durAvg FROM (SELECT * FROM indata ORDER BY duration LIMIT 2 OFFSET 6)"
0
source

Source: https://habr.com/ru/post/1755933/


All Articles