2010-06-06 76 views
5

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

这是我迄今为止所做的,但它不是很好。我添加了评论,我需要添加taks & 。
任何建议或代码来完成上述任务将是伟大的!谢谢。

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 

    } 

再次感谢您的帮助。 =]

+1

你会发现你会得到更多更好的答案,如果你真的问一个问题。 – 2010-06-06 01:57:15

回答

5

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

+0

我下载了opencsv,但我不知道如何使用库。请你指点我正确的方向。我使用netbeans – nubme 2010-06-06 02:17:51

+0

有关使用opencsv进行读写的示例,请参阅http://opencsv.sourceforge.net/#how-to-read – seangrieve 2010-06-06 02:32:02

1

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

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

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

1

由于Java不支持CSV文件解析本身,我们必须依靠第三方库。 Opencsv是可用于此目的的最佳图书馆之一。它是开源的,并附带Apache 2.0许可证,这使得商业用途成为可能。

在这里,this link应该帮助你和其他人的情况!

1

与开源库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<Inventory> rowProcessor = new BeanListProcessor<Inventory>(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<Inventory> storeInvList = rowProcessor.getBeans(); 
    Iterator<Inventory> storeInvIterator = storeInvList.iterator(); 

    parser.parse(new FileReader("/src/test/new_acquisitions.csv")); 
    List<Inventory> newAcqList = rowProcessor.getBeans(); 
    Iterator<Inventory> 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和出色的性能。

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> objects = new ArrayList<Objects>(); 
     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<String> record = new ArrayList<String>(); 

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