Modifying complex csv files in java

前端 未结 2 980
时光说笑
时光说笑 2021-01-21 15:46

I wanted to write a program which can print, and modify the irregular csv files. The format is as follows:

    1.date
    2.organization name
    3. student name         


        
2条回答
  •  死守一世寂寞
    2021-01-21 16:35

    Try uniVocity-parsers to handle this. For parsing this sort of format, you'll find a few examples here. For writing, look here and here.

    Adapting from the examples I've given, you could write:

    final ObjectRowListProcessor dateProcessor = new ObjectRowListProcessor();
    final ObjectRowListProcessor clubProcessor = new ObjectRowListProcessor();
    final ObjectRowListProcessor memberProcessor = new ObjectRowListProcessor();
    
    InputValueSwitch switch = new InputValueSwitch(0){
        public void rowProcessorSwitched(RowProcessor from, RowProcessor to) {
        //your custom logic here
        if (to == dateProcessor) {
            //processing dates.
        }
        if (to == clubProcessor) {
            //processing clubs.
        }
        if (to == memberProcessor){
            //processing members
        }
    };
    
    switch.addSwitchForValue("1.", dateProcessor, 1);  //getting values of column 1 and sending them to `dateProcessor`
    switch.addSwitchForValue("2.", clubProcessor, 1); //getting values of column 1 and sending them to `clubProcessor`
    switch.addSwitchForValue("3.", memberProcessor, 1, 2, 3); //getting values of columns 1, 2, and 3 and sending them to `memberProcessor` 
    setDefaultSwitch(memberProcessor, 1, 2, 3); //Rows with blank value at column 0 are members. Also get columns 1, 2, and 3 and send them to `memberProcessor`
    
    CsvParserSettings settings = new CsvParserSettings(); //many options here, check the tutorial and examples
    
    // configure the parser to use the switch
    settings.setRowProcessor(switch);
    
    //creates a parser
    CsvParser parser = new CsvParser(settings);
    
    //parse everying. Rows will be sent to the RowProcessor of each switch, depending on the value at column 0.
    parser.parse(new File("/path/to/file.csv")); 
    

    Disclaimer: I'm the author of this library, it's open-source and free (Apache 2.0 license)

提交回复
热议问题