Java:CSV文件读写

我正在阅读2个csv文件: store_inventorynew_acquisitions
我希望能够将store_inventory csv文件与new_acquisitions进行比较。 1)如果项目名称匹配,则只更新store_inventory中的数量。 2)如果new_acquisitions有一个store_inventory中不存在的新项目,则将其添加到store_inventory

这是我到目前为止所做的,但不是很好。 我添加了评论,我需要添加12
任何做上述任务的建议或代码都会很棒! 谢谢。

  File new_acq = new File("/src/test/new_acquisitions.csv"); Scanner acq_scan = null; try { acq_scan = new Scanner(new_acq); } catch (FileNotFoundException ex) { Logger.getLogger(mainpage.class.getName()).log(Level.SEVERE, null, ex); } String itemName; int quantity; Double cost; Double price; File store_inv = new File("/src/test/store_inventory.csv"); Scanner invscan = null; try { invscan = new Scanner(store_inv); } catch (FileNotFoundException ex) { Logger.getLogger(mainpage.class.getName()).log(Level.SEVERE, null, ex); } String itemNameInv; int quantityInv; Double costInv; Double priceInv; while (acq_scan.hasNext()) { String line = acq_scan.nextLine(); if (line.charAt(0) == '#') { continue; } String[] split = line.split(","); itemName = split[0]; quantity = Integer.parseInt(split[1]); cost = Double.parseDouble(split[2]); price = Double.parseDouble(split[3]); while(invscan.hasNext()) { String line2 = invscan.nextLine(); if (line2.charAt(0) == '#') { continue; } String[] split2 = line2.split(","); itemNameInv = split2[0]; quantityInv = Integer.parseInt(split2[1]); costInv = Double.parseDouble(split2[2]); priceInv = Double.parseDouble(split2[3]); if(itemName == itemNameInv) { //update quantity } } //add new entry into csv file } 

再次感谢任何帮助。 =]

建议您使用现有的CSV解析器之一,如Commons CSV或Super CSV,而不是重新发明轮子。 应该让你的生活更轻松。

您的实现通常使用line.split(",")line.split(",")逗号中的行。 这不起作用,因为值本身可能包含逗号。 如果发生这种情况,则必须引用该值,并且您需要忽略引号中的逗号。 split方法不能这样做 – 我经常看到这个错误。

以下是正确执行的实现的来源: http : //agiletribe.wordpress.com/2012/11/23/the-only-class-you-need-for-csv-files/

在开源库uniVocity-parsers的帮助下,您可以使用非常干净的代码进行开发,如下所示:

 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); } } } 

只需按照我根据您的要求制定的代码示例。 请注意,该库为解析CSV文件提供了简化的API和卓越的性能。

您正在执行的操作将要求对于新采购中的每个项目,您需要搜索库存中的每个项目以进行匹配。 这不仅效率不高,而且您为库存文件设置的扫描仪需要在每个项目后重置。

我建议您将新的收购和库存添加到collections中,然后迭代新的收购并在库存收集中查找新项目。 如果该项目存在,请更新该项目。 如果没有,请将其添加到库存集合中。 对于此活动,编写一个包含库存项目的简单类可能会很好。 它可以用于新的收购和库存。 对于快速查找,我建议您使用HashSet或HashMap作为库存集合。

在此过程结束时,不要忘记将更改保留到您的库存文件中。

由于Java本身不支持解析CSV文件,因此我们必须依赖第三方库。 Opencsv是可用于此目的的最佳库之一。 它是开源的,附带Apache 2.0许可证,可以用于商业用途。

在这里, 这个链接应该帮助你和其他人在这种情况下!

用于写入CSV

 public void writeCSV() { // Delimiter used in CSV file private static final String NEW_LINE_SEPARATOR = "\n"; // CSV file header private static final Object[] FILE_HEADER = { "Empoyee Name","Empoyee Code", "In Time", "Out Time", "Duration", "Is Working Day" }; String fileName = "fileName.csv"); List objects = new ArrayList(); FileWriter fileWriter = null; CSVPrinter csvFilePrinter = null; // Create the CSVFormat object with "\n" as a record delimiter CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR); try { fileWriter = new FileWriter(fileName); csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat); csvFilePrinter.printRecord(FILE_HEADER); // Write a new student object list to the CSV file for (Object object : objects) { List record = new ArrayList(); record.add(object.getValue1().toString()); record.add(object.getValue2().toString()); record.add(object.getValue3().toString()); csvFilePrinter.printRecord(record); } } catch (Exception e) { e.printStackTrace(); } finally { try { fileWriter.flush(); fileWriter.close(); csvFilePrinter.close(); } catch (IOException e) { e.printStackTrace(); } } } 

您可以使用Apache Commons CSV api。 仅供参考: https ://stackoverflow.com/a/42198895/6549532

读/写示例