Java:CSV文件读写

nub*_*bme 5 java csv file java.util.scanner

我正在阅读2个csv文件:store_inventory&new_acquisitions.
我希望能够比较store_inventorycsv文件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

     }
Run Code Online (Sandbox Code Playgroud)

再次感谢任何帮助.=]

obj*_*cts 5

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