我正在使用csvwriter编写一个csv文件,然后调用它的方法writeAll。写完后我使用缓冲读取器读取相同的文件,导致数字格式异常。我该如何解决?
public static void writeInventoryToUpdate(List<String[]> data)throws IOException {
String csv = "E:\\Semester 3\\PointOfSale2\\Inventory.csv";
CSVWriter writer = new CSVWriter(new FileWriter(csv));
writer.writeAll(data);
writer.close();
}
public void initInventory() throws FileNotFoundException, IOException {
BufferedReader readInventory=new BufferedReader(new FileReader("E:\\Semester 3\\PointOfSale2\\Inventory.csv"));
String line=readInventory.readLine();
StringTokenizer nextItem;
while(line!=null){
nextItem=new StringTokenizer(line, ",");
while(nextItem.hasMoreTokens()){
int productID=Integer.parseInt(nextItem.nextToken()); //Exception occuring here
int quantity=Integer.parseInt(nextItem.nextToken());
Inventory inventory=new Inventory(productID, quantity);
inStock.add(inventory);
line=readInventory.readLine();
}
}
readInventory.close();
}
答案 0 :(得分:0)
你的代码大多是正确的想法,但有关于它的流程的一些问题
BufferedReader readInventory=new BufferedReader(new FileReader("E:\\Semester 3\\PointOfSale2\\Inventory.csv"));
for(String line = readInventory.readLine(); line != null; line = readInventory.readLine())
{
StringTokenizer nextItem = new StringTokenizer(line, ",");
if(nextItem.countTokens() >= 2)
{
int productID = Integer.parseInt(nextItem.nextToken());
int quantity = Integer.parseInt(nextItem.nextToken());
Inventory inventory=new Inventory(productID, quantity);
inStock.add(inventory);
}
}
readInventory.close();
根据输入
,这里应该有用12345,67890
15243,60798
3,6
77,12355678,123 //anything past the first two values are ignored
555
777,333 //and single value things are skipped
如果没有看到您尝试解析的CSV文件类型,我无法为您提供更好的解决方案
但是对于CSV文件的最基本形式(两个用逗号分隔的int值),这应该可以正常工作