I am trying to write to a csv file however everytime i get a null pointer exception. The data i wanted written to the csv file is being written but i get the error and i cant figure out why.
public static void writeCsvFile() {
FileWriter fw = null;
VendingMachine vm = new VendingMachine("Conall", 10);
try {
fw = new FileWriter("stock.txt");
//fw.append("ID");
for (VendItem item : stock) {
fw.append(String.valueOf(item.getId()));
fw.append(",");
fw.append(item.getName());
fw.append(",");
fw.append(String.valueOf(item.getPrice()));
fw.append(",");
fw.append(String.valueOf(item.getPrice()));
fw.append("\n");
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
fw.flush();
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
My file has the following in it:
1,Coke,0.7,0.7
2,Fanta,0.6,0.6
3,Galaxy,1.2,1.2
4,Snickers,1.0,1.0
5,Dairy Milk,1.3,1.3
6,Kinder,1.3,1.3
How can i fix the null pointer error as it seems to be working as i am looking it to, i.e writing the files in my stock to this file.
Thanks for any help