2010-06-06 35 views
5

Sto leggendo 2 file CSV: store_inventorynew_acquisitions.
Desidero poter confrontare il file csv store_inventory con new_acquisitions. 1) Se i nomi delle voci corrispondono, aggiornare la quantità in store_inventory. 2) Se new_acquisitions ha un nuovo elemento che non esiste in store_inventory, quindi aggiungerlo allo store_inventory.Java: file CSV in lettura e scrittura

Ecco cosa ho fatto finora ma non è molto buono. Ho aggiunto commenti dove ho bisogno di aggiungere taks & .
Qualsiasi consiglio o codice per eseguire i compiti sopra elencati sarebbe fantastico! Grazie.

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 

    } 

Grazie ancora per qualsiasi aiuto. =]

+1

Troverete che si ottiene di più e meglio le risposte se si chiede in realtà una domanda. –

risposta

5

Suggerisci di utilizzare uno dei parser CSV esistenti come Commons CSV o Super CSV invece di reinventare la ruota. Dovrebbe rendere la tua vita molto più facile.

+0

Ho scaricato opencsv, ma non ho idea di come usare la libreria. Potrebbe indicarmi la direzione giusta per favore. Sto usando netbeans – nubme

+0

Per esempi su lettura e scrittura con opencsv, vedi http://opencsv.sourceforge.net/#how-to-read – seangrieve

1

L'operazione che si sta eseguendo richiederà che per ogni articolo nelle nuove acquisizioni, sarà necessario cercare ogni elemento nell'inventario per una corrispondenza. Questo non è solo non efficiente, ma lo scanner che hai impostato per il tuo file di inventario dovrebbe essere ripristinato dopo ogni elemento.

Ti suggerisco di aggiungere le tue nuove acquisizioni e il tuo inventario alle raccolte e quindi scorrere le tue nuove acquisizioni e cercare il nuovo elemento nella tua collezione di inventario. Se l'articolo esiste, aggiorna l'oggetto. Se non lo fa, aggiungilo alla collezione di inventario. Per questa attività, potrebbe essere utile scrivere una classe semplice per contenere un elemento di inventario. Potrebbe essere utilizzato sia per le nuove acquisizioni che per l'inventario. Per una rapida ricerca, ti suggerirei di utilizzare HashSet o HashMap per la tua collezione di inventario.

Al termine del processo, non dimenticare di mantenere le modifiche al file di inventario.

3

L'implementazione commette l'errore comune di suddividere la riga in virgole utilizzando line.split(","). Questo non funziona perché i valori stessi potrebbero avere virgole in essi. Se ciò accade, il valore deve essere quotato e devi ignorare le virgole tra virgolette. Il metodo split non può farlo - vedo questo errore molto.

Qui è la sorgente di un'implementazione che lo fa in modo corretto: http://agiletribe.wordpress.com/2012/11/23/the-only-class-you-need-for-csv-files/

1

Come Java non supporta l'analisi di file CSV in modo nativo, dobbiamo fare affidamento sulla libreria di terze parti. Opencsv è una delle migliori librerie disponibili per questo scopo. È open source e viene fornito con licenza Apache 2.0 che rende possibile l'uso commerciale.

Qui, this link dovrebbe aiutare te e gli altri nelle situazioni!

1

Con l'aiuto della libreria open source uniVocity-parsers, si potrebbe sviluppare con il codice abbastanza pulito come segue:

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

basta seguire questo esempio di codice ho lavorato in base alle proprie esigenze. Si noti che la libreria ha fornito API semplificate e prestazioni significative per l'analisi dei file CSV.

0

Per la scrittura in formato 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(); 
      } 
     } 
    }