Java: CSV file read & write

前端 未结 7 1523
南旧
南旧 2020-12-10 08:18

I\'m reading 2 csv files: store_inventory & new_acquisitions.
I want to be able to compare the store_inventory csv file with <

7条回答
  •  春和景丽
    2020-12-10 08:42

    With help of the open source library uniVocity-parsers, you could develop with pretty clean code as following:

    private void processInventory() throws IOException {
        /**
         * ---------------------------------------------
         *  Read CSV rows into list of beans you defined
         * ---------------------------------------------
         */
        // 1st, config the CSV reader with row processor attaching the bean definition
        CsvParserSettings settings = new CsvParserSettings();
        settings.getFormat().setLineSeparator("\n");
        BeanListProcessor rowProcessor = new BeanListProcessor(Inventory.class);
        settings.setRowProcessor(rowProcessor);
        settings.setHeaderExtractionEnabled(true);
    
        // 2nd, parse all rows from the CSV file into the list of beans you defined
        CsvParser parser = new CsvParser(settings);
        parser.parse(new FileReader("/src/test/store_inventory.csv"));
        List storeInvList = rowProcessor.getBeans();
        Iterator storeInvIterator = storeInvList.iterator();
    
        parser.parse(new FileReader("/src/test/new_acquisitions.csv"));
        List newAcqList = rowProcessor.getBeans();
        Iterator newAcqIterator = newAcqList.iterator();
    
        // 3rd, process the beans with business logic
        while (newAcqIterator.hasNext()) {
    
            Inventory newAcq = newAcqIterator.next();
            boolean isItemIncluded = false;
            while (storeInvIterator.hasNext()) {
                Inventory storeInv = storeInvIterator.next();
    
                // 1) If the item names match just update the quantity in store_inventory
                if (storeInv.getItemName().equalsIgnoreCase(newAcq.getItemName())) {
                    storeInv.setQuantity(newAcq.getQuantity());
                    isItemIncluded = true;
                }
            }
    
            // 2) If new_acquisitions has a new item that does not exist in store_inventory,
            // then add it to the store_inventory.
            if (!isItemIncluded) {
                storeInvList.add(newAcq);
            }
        }
    }
    

    Just follow this code sample I worked out according to your requirements. Note that the library provided simplified API and significent performance for parsing CSV files.

提交回复
热议问题