Java:CSV文件读取&写
我正在读取 2 个 csv 文件:store_inventory
& new_acquisitions
。
我希望能够将 store_inventory
csv 文件与 new_acquisitions
进行比较。 1) 如果商品名称匹配,只需更新 store_inventory 中的数量。 2) 如果 new_acquisitions 有 store_inventory
中不存在的新项目,则将其添加到 store_inventory
中。
这是我到目前为止所做的,但效果不是很好。我在需要添加任务 1 & 的地方添加了评论。 2。
任何执行上述任务的建议或代码都会很棒!谢谢。
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
}
再次感谢您的帮助。 =]
I'm reading 2 csv files: store_inventory
& new_acquisitions
.
I want to be able to compare the store_inventory
csv file with new_acquisitions
.
1) If the item names match just update the quantity in store_inventory.
2) If new_acquisitions has a new item that does not exist in store_inventory
, then add it to the store_inventory
.
Here is what i have done so far but its not very good. I added comments where i need to add taks 1 & 2.
Any advice or code to do the above tasks would be great! thanks.
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
}
Thanks again for any help. =]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
建议您使用现有的 CSV 解析器之一,例如 Commons CSV 或 超级 CSV 而不是重新发明轮子。应该会让你的生活变得更轻松。
Suggest you use one of the existing CSV parser such as Commons CSV or Super CSV instead of reinventing the wheel. Should make your life a lot easier.
在开源库 uniVocity-parsers 的帮助下,您可以使用非常干净的代码进行开发,如下所示以下:
只需按照我根据您的要求制定的代码示例即可。请注意,该库提供了简化的 API 和解析 CSV 文件的显着性能。
With help of the open source library uniVocity-parsers, you could develop with pretty clean code as following:
Just follow this code sample I worked out according to your requirements. Note that the library provided simplified API and significent performance for parsing CSV files.
您正在执行的操作将要求对于新采购中的每件商品,您都需要在库存中搜索每件商品以查找匹配项。这不仅效率低下,而且您为库存文件设置的扫描仪需要在每个项目之后重置。
我建议您将新购买的商品和库存添加到集合中,然后迭代新购买的商品并在库存集合中查找新商品。如果该项目存在,则更新该项目。如果没有,请将其添加到库存集合中。对于此活动,最好编写一个简单的类来包含库存项目。它可用于新采购和库存。为了快速查找,我建议您使用 HashSet 或 HashMap 来进行库存集合。
在此过程结束时,不要忘记保留对库存文件的更改。
The operation you are performing will require that for each item in your new acquisitions, you will need to search each item in inventory for a match. This is not only not efficient, but the scanner that you have set up for your inventory file would need to be reset after each item.
I would suggest that you add your new acquisitions and your inventory to collections and then iterate over your new acquisitions and look up the new item in your inventory collection. If the item exists, update the item. If it doesnt, add it to the inventory collection. For this activity, it might be good to write a simple class to contain an inventory item. It could be used for both the new acquisitions and for the inventory. For a fast lookup, I would suggest that you use HashSet or HashMap for your inventory collection.
At the end of the process, dont forget to persist the changes to your inventory file.
由于Java本身不支持CSV文件的解析,因此我们必须依赖第三方库。 Opencsv 是可用于此目的的最佳库之一。它是开源的,并附带 Apache 2.0 许可证,这使得它可以用于商业用途。
在这里,此链接应该可以帮助您和其他人解决这种情况!
As Java doesn’t support parsing of CSV files natively, we have to rely on third party library. Opencsv is one of the best library available for this purpose. It’s open source and is shipped with Apache 2.0 licence which makes it possible for commercial use.
Here, this link should help you and others in the situations!
用于写入 CSV
For writing to CSV
您可以使用 Apache Commons CSV api。
仅供参考:https://stackoverflow.com/a/42198895/6549532
读/写示例
You can use Apache Commons CSV api.
FYI this anwser : https://stackoverflow.com/a/42198895/6549532
Read / Write Example
您的实现犯了一个常见错误,即使用 line.split(",") 在逗号上换行。这不起作用,因为值本身可能包含逗号。如果发生这种情况,则必须将该值加引号,并且您需要忽略引号内的逗号。 split 方法不能做到这一点——我经常看到这个错误。
有一些开源库支持这一点。我试图链接一个,但我的答案被删除了,因为它被认为是自我推销。环顾四周,有一些库可以正确地做到这一点。
Your implementation makes the common mistake of breaking the line on commas by using line.split(","). This does not work because the values themselves might have commas in them. If that happens, the value must be quoted, and you need to ignore commas within the quotes. The split method can not do this -- I see this mistake a lot.
There are open source libraries that support this. I tried to link one but my answer got deleted because it was considered self promotion. Go look around, there are libraries that can do this correctly.