2010-06-06 51 views
5

Tôi đang đọc 2 tệp csv: store_inventory & new_acquisitions.
Tôi muốn có thể so sánh tệp store_inventory csv với new_acquisitions. 1) Nếu tên mục khớp với chỉ cập nhật số lượng trong store_inventory. 2) Nếu new_acquisitions có một mục mới không tồn tại trong store_inventory, sau đó thêm nó vào store_inventory.Java: Tệp CSV đọc & ghi

Đây là những gì tôi đã làm cho đến nay nhưng nó không phải là rất tốt. Tôi đã thêm nhận xét mà tôi cần thêm taks & .
Bất kỳ lời khuyên hay mã nào để thực hiện các tác vụ trên sẽ rất tuyệt vời! cảm ơn.

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 

    } 

Cảm ơn bạn một lần nữa. =]

+1

Bạn sẽ tìm thấy bạn nhận được nhiều hơn và tốt hơn câu trả lời nếu bạn thực sự đặt một câu hỏi. –

Trả lời

5

Đề xuất bạn sử dụng một trong các trình phân tích cú pháp CSV hiện tại chẳng hạn như Commons CSV hoặc Super CSV thay vì phát minh lại bánh xe. Nên làm cho cuộc sống của bạn dễ dàng hơn nhiều.

+0

Tôi đã tải xuống opencsv, nhưng tôi không biết cách sử dụng thư viện. Bạn có thể chỉ cho tôi đi đúng hướng được không. Im sử dụng netbeans – nubme

+0

Ví dụ về đọc và viết với opencsv, xem http://opencsv.sourceforge.net/#how-to-read – seangrieve

1

Thao tác bạn đang thực hiện sẽ yêu cầu đối với mỗi mục trong lần mua lại mới, bạn sẽ cần phải tìm kiếm từng mục trong khoảng không quảng cáo cho phù hợp. Điều này không chỉ không hiệu quả, nhưng máy quét mà bạn đã thiết lập cho tệp khoảng không quảng cáo của bạn sẽ cần được đặt lại sau mỗi mục.

Tôi khuyên bạn nên thêm các chuyển đổi mới và khoảng không quảng cáo của mình vào bộ sưu tập và sau đó lặp lại các lần mua lại mới và tìm kiếm mục mới trong bộ sưu tập khoảng không quảng cáo của bạn. Nếu mục đó tồn tại, hãy cập nhật mục. Nếu không, hãy thêm nó vào bộ sưu tập khoảng không quảng cáo. Đối với hoạt động này, bạn có thể viết một lớp đơn giản để chứa một mục hàng tồn kho. Nó có thể được sử dụng cho cả việc mua lại mới và cho khoảng không quảng cáo. Để tra cứu nhanh, tôi khuyên bạn nên sử dụng HashSet hoặc HashMap cho bộ sưu tập khoảng không quảng cáo của mình.

Khi kết thúc quá trình, đừng quên duy trì các thay đổi đối với tệp khoảng không quảng cáo của bạn.

3

Việc triển khai của bạn làm cho sai lầm phổ biến là vi phạm dòng trên dấu phẩy bằng cách sử dụng line.split(","). Điều này không hoạt động bởi vì các giá trị tự có thể có dấu phẩy trong chúng. Nếu điều đó xảy ra, giá trị phải được trích dẫn và bạn cần phải bỏ qua dấu phẩy trong dấu ngoặc kép. Phương pháp split không thể làm được điều này - tôi thấy sai lầm này rất nhiều.

Đây là nguồn gốc của một thực hiện mà không một cách chính xác: http://agiletribe.wordpress.com/2012/11/23/the-only-class-you-need-for-csv-files/

1

Như Java không hỗ trợ phân tích các tập tin CSV natively, chúng ta phải dựa vào thư viện của bên thứ ba. Opencsv là một trong những thư viện tốt nhất có sẵn cho mục đích này. Đó là mã nguồn mở và được vận chuyển với giấy phép Apache 2.0, điều này có thể sử dụng cho mục đích thương mại.

Ở đây, this link sẽ giúp bạn và những người khác trong các tình huống!

1

Với sự giúp đỡ của thư viện mã nguồn mở uniVocity-parsers, bạn có thể phát triển với mã đẹp, sạch sẽ như sau:

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

Chỉ cần làm theo mẫu mã này, tôi đưa ra theo yêu cầu của bạn. Lưu ý rằng thư viện cung cấp API đơn giản và hiệu suất có ý nghĩa để phân tích cú pháp các tệp CSV.

0

Đối với văn bản cho 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(); 
      } 
     } 
    } 
Các vấn đề liên quan