1

我使用FasterXML 库来解析我的CSV file. 第一CSV file 行有列名。不幸的是,我需要重命名列。我有一个 lambda 函数,我可以在其中传递红色值csv filein 传递红色值并获取新值。

我的代码看起来像这样,但不起作用。

CsvSchema csvSchema =CsvSchema.emptySchema().withHeader();
ArrayList<HashMap<String, String>> result = new ArrayList<HashMap<String, String>>();       
MappingIterator<HashMap<String,String>> it = new CsvMapper().reader(HashMap.class)
                                                    .with(csvSchema )
                                                    .readValues(new File(fileName));
            
            
            while (it.hasNext()) 
              result.add(it.next());
            
        
            System.out.println("changing the schema columns.");

            for (int i=0; i < csvSchema.size();i++) { 
                
                String name = csvSchema.column(i).getName();
                String newName = getNewName(name);
                csvSchema.builder().renameColumn(i, newName);
                
            }
            csvSchema.rebuild();

当我稍后尝试打印出这些列时,它们仍然与我的第一行相同CSV file.

另外我注意到,这csvSchema.size()等于0- 为什么?

4

1 回答 1

2

您可以改为使用uniVocity-parsers。以下解决方案将输入行流式传输到输出,因此您无需将所有内容加载到内存中,然后使用新标题将数据写回。它会更快:

public static void main(String ... args) throws Exception{

    Writer output = new StringWriter(); // use a FileWriter for your case

    CsvWriterSettings writerSettings = new CsvWriterSettings(); //many options here - check the documentation
    final CsvWriter writer = new CsvWriter(output, writerSettings);

    CsvParserSettings parserSettings = new CsvParserSettings();  //many options here as well
    parserSettings.setHeaderExtractionEnabled(true); // indicates the first row of the input are headers

    parserSettings.setRowProcessor(new AbstractRowProcessor(){

        public void processStarted(ParsingContext context) {
            writer.writeHeaders("Column A", "Column B", "... etc");
        }

        public void rowProcessed(String[] row, ParsingContext context) {
            writer.writeRow(row);
        }

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

    CsvParser parser = new CsvParser(parserSettings);
    Reader reader = new StringReader("A,B,C\n1,2,3\n4,5,6"); // use a FileReader for your case
    parser.parse(reader); // all rows are parsed and submitted to the RowProcessor implementation of the parserSettings.

    System.out.println(output.toString());
    //nothing else to do. All resources are closed automatically in case of errors.
}

parserSettings.selectFields("B", "A")如果您想重新排序/消除列,您可以通过使用轻松选择列。

披露:我是这个库的作者。它是开源和免费的(Apache V2.0 许可证)。

于 2015-06-30T20:57:11.150 回答