2016-05-26 3 views
1

私は異なる列ヘッダーを持つ多くのCSVファイルを持っています。現在、私はそれらのcsvファイルを読んでいて、それらの列ヘッダーに基づいて異なるPOJOクラスにマップしています。そのため、CSVファイルの中には、POJOクラスを作成することが困難な約100個のカラムヘッダーがあります。1つのPOJOに複数のCSVをマップ

私は単一のpojoを使うことができるテクニックがあるので、これらのcsvファイルを読み込むと、1つのPOJOクラスにマップできます。または、CSVファイルを1行ずつ読み込んでそれに応じて解析するか、実行時にPOJOを作成する必要があります。 (javaassist)?

+1

POJOではなくマップを使用することを検討しましたか? –

答えて

0

私が正しくあなたの問題を理解していれば、あなたはこれを処理し、マップ内のデータを取得するためにuniVocity-parsersを使用することができます。

//First create a configuration object - there are many options 
//available and the tutorial has a lot of examples 
CsvParserSettings settings = new CsvParserSettings(); 
settings.setHeaderExtractionEnabled(true); 

CsvParser parser = new CsvParser(settings); 
parser.beginParsing(new File("/path/to/your.csv")); 

// you can also apply some transformations: 
// NULL year should become 0000 
parser.getRecordMetadata().setDefaultValueOfColumns("0000", "Year"); 

// decimal separator in prices will be replaced by comma 
parser.getRecordMetadata().convertFields(Conversions.replace("\\.00", ",00")).set("Price"); 

Record record; 
while ((record = parser.parseNextRecord()) != null) { 
    Map<String, String> map = record.toFieldMap(/*you can pass a list of column names of interest here*/); 
    //for performance, you can also reuse the map and call record.fillFieldMap(map); 
} 

それともでもファイルを解析し、単一段階でさまざまな種類の豆を得ることができます。ここではあなたがそれを行う方法は次のとおりです。あなたのデータが大きすぎると、あなたが使用して行で入力行をストリーミングすることができ、メモリ内のすべてを保持することができない場合

CsvParserSettings settings = new CsvParserSettings(); 

//Create a row processor to process input rows. In this case we want 
//multiple instances of different classes: 
MultiBeanListProcessor processor = new MultiBeanListProcessor(TestBean.class, AmountBean.class, QuantityBean.class); 

// we also need to grab the headers from our input file 
settings.setHeaderExtractionEnabled(true); 

// configure the parser to use the MultiBeanProcessor 
settings.setRowProcessor(processor); 

// create the parser and run 
CsvParser parser = new CsvParser(settings); 

parser.parse(new File("/path/to/your.csv")); 

// get the beans: 
List<TestBean> testBeans = processor.getBeans(TestBean.class); 
List<AmountBean> amountBeans = processor.getBeans(AmountBean.class); 
List<QuantityBean> quantityBeans = processor.getBeans(QuantityBean.class); 

は例herehere

を参照してください。代わりにMultiBeanRowProcessorメソッドrowProcessed(Map<Class<?>, Object> row, ParsingContext context)は、現在の行の各クラスに対して作成されたインスタンスのマップを提供します。メソッド内では、

AmountBean amountBean = (AmountBean) row.get(AmountBean.class); 
QuantityBean quantityBean = (QuantityBean) row.get(QuantityBean.class); 
... 

//perform something with the instances parsed in a row. 

を呼び出すだけです。

免責事項:私はこのライブラリの作者です。それはオープンソースでフリーです(Apache 2.0ライセンス)

0

私にとって、POJOクラスの作成はこの場合はお勧めできません。列数もファイル数も一定ではないため、 したがって、より多くの列またはファイルをサポートするためにコードを大幅に変更する必要がない、より動的なものを使用する方がよいでしょう。

私は与えられたCSVファイルのMapList<Map<>>List(またはMap)のために行くだろう。 各mapは、列名としてkeyでcsvファイルの行を表します。

複数のcsvファイルに簡単に拡張できます。

関連する問題