0

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

Cbrady
  • 93
  • 1
  • 2
  • 7

1 Answers1

0

You did not specify a file path for your file "stock.txt". Your program will only know where "stock.txt" is if it is located in your project folder, not your source folder. If your file is somewhere else- in your documents folder, for example, you should specify an absolute or relative file path.

  • Yeah i realised that then made a variable private String filePath ="C:\\Users\\conall\\desktop\\stock.txt"; and put String filePath as my parameters in the method. Still not working – Cbrady Apr 03 '20 at 01:31
  • You could try to pass a file object into the FileWriter. FileWriter fw = new FileWriter(new File("path goes here")); – Isaiah Dicristoforo Apr 03 '20 at 01:39
  • Still getting java.lang.NullPointerException – Cbrady Apr 03 '20 at 01:46