我有許多帶有不同列標題的CSV文件。目前我正在閱讀這些csv文件,並根據它們的列標題將它們映射到不同的POJO類。所以一些CSV文件有大約100個列標題,這使得難以創建POJO類。將多個CSV映射到單個POJO
因此,是否有任何技術可以使用單個pojo,因此當讀取這些csv文件可以映射到單個POJO類時,或者我應該逐行讀取CSV文件並相應地進行解析,或者我應該在運行時創建POJO (javaassist)?
我有許多帶有不同列標題的CSV文件。目前我正在閱讀這些csv文件,並根據它們的列標題將它們映射到不同的POJO類。所以一些CSV文件有大約100個列標題,這使得難以創建POJO類。將多個CSV映射到單個POJO
因此,是否有任何技術可以使用單個pojo,因此當讀取這些csv文件可以映射到單個POJO類時,或者我應該逐行讀取CSV文件並相應地進行解析,或者我應該在運行時創建POJO (javaassist)?
如果我正確理解你的問題,你可以使用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);
如果你的數據量太大,你不能保留在內存中的一切,你可以通過使用由排流的輸入行改爲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許可證)
對我而言,在這種情況下創建一個POJO類並不是一個好主意。由於列數和文件數量都不是固定的。 因此,最好使用更動態的東西,爲了支持更多的列或文件,您無需在很大程度上更改代碼。
對於給定的csv文件,我會去List
(或Map
)的Map
List<Map<>>
。 其中每個map
代表您的csv文件中的一行,並且列名稱爲key
。
您可以輕鬆將其擴展爲多個csv文件。
你有沒有考慮過使用Map而不是POJO? –