2010-06-06 32 views
5

Estoy leyendo 2 archivos csv: store_inventory & new_acquisitions.
Quiero poder comparar el archivo store_inventory csv con new_acquisitions. 1) Si los nombres de los elementos coinciden, actualice la cantidad en store_inventory. 2) Si new_acquisitions tiene un nuevo elemento que no existe en store_inventory, agréguelo al store_inventory.Java: archivo CSV de lectura y escritura

Esto es lo que he hecho hasta ahora pero no es muy bueno. Agregué comentarios donde necesito agregar taks & .
¡Cualquier consejo o código para realizar las tareas anteriores sería genial! Gracias.

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 

    } 

Gracias de nuevo por cualquier ayuda. =]

+1

Encontrarás a obtener más y mejores respuestas si realmente hace una pregunta. –

Respuesta

5

Le sugerimos que use uno de los analizadores CSV existentes como Commons CSV o Super CSV en lugar de reinventar la rueda. Debería hacer su vida mucho más fácil.

+0

Descargué Opencsv, pero no tengo idea de cómo usar la biblioteca. ¿Podría señalarme en la dirección correcta, por favor? Estoy usando netbeans – nubme

+0

Para ver ejemplos sobre cómo leer y escribir con opencsv, consulte http://opencsv.sourceforge.net/#how-to-read – seangrieve

1

La operación que está realizando requerirá que para cada artículo en sus nuevas adquisiciones, tendrá que buscar cada partida del inventario para una coincidencia. Esto no solo no es eficiente, sino que el escáner que haya configurado para su archivo de inventario deberá reiniciarse después de cada elemento.

Le sugiero que agregue sus nuevas adquisiciones y su inventario a las colecciones y luego itere sobre sus nuevas adquisiciones y busque el nuevo elemento en su colección de inventario. Si el artículo existe, actualiza el artículo. Si no lo hace, agréguelo a la colección de inventario. Para esta actividad, podría ser bueno escribir una clase simple para contener un elemento del inventario. Podría usarse tanto para las nuevas adquisiciones como para el inventario. Para una búsqueda rápida, le sugiero que use HashSet o HashMap para su colección de inventario.

Al final del proceso, no se olvide de conservar los cambios en su archivo de inventario.

3

Su implementación comete el error común de romper la línea en comas usando line.split(","). Esto no funciona porque los valores mismos pueden tener comas en ellos. Si eso sucede, el valor debe citarse, y debe ignorar las comas dentro de las comillas. El método split no puede hacer esto: veo este error mucho.

Aquí es la fuente de una aplicación que lo hace correctamente: http://agiletribe.wordpress.com/2012/11/23/the-only-class-you-need-for-csv-files/

1

como Java no soporta análisis de los archivos CSV de forma nativa, tenemos que confiar en la biblioteca de terceros. Opencsv es una de las mejores bibliotecas disponibles para este propósito. Es de código abierto y se envía con una licencia Apache 2.0 que permite su uso comercial.

¡Aquí, this link debería ayudarlo a usted y a otros en las situaciones!

1

Con la ayuda de la biblioteca de código abierto uniVocity-parsers, se podría desarrollar con código bastante limpio de la siguiente manera:

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

sólo tienes que seguir este ejemplo de código que trabajé a cabo de acuerdo a sus necesidades. Tenga en cuenta que la biblioteca proporcionó una API simplificada y un rendimiento magnífico para analizar archivos CSV.

0

Para escribir a 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(); 
      } 
     } 
    } 
Cuestiones relacionadas