Bufferedwriter works, but file empty?

newnewbie picture newnewbie · Sep 2, 2013 · Viewed 8.3k times · Source

I have the following code:

CSVmaker(LinkedList data) {
    String [] myLines = makeStrings(data);
  //  for (int k = 0; k<myLines.length; k++)
  //  System.out.println(myLines[]);




    this.file = new File("rawdata.csv");
        try {
            BufferedWriter buff = new BufferedWriter(new FileWriter(file));
            for (int i = 0; i<myLines.length; i++){
                buff.write(myLines[i]);
                buff.newLine();
                System.out.println("done");
            }
        } catch (IOException ex) {
          System.out.println("except");
        }



}

No, I checked for the contents of myLines, these are correct.

Also, I get the print which prints "done" just as often as I should. The csv is created.

However, if I open it manually, it is empty.

What can be the reason for this?

Answer

nanofarad picture nanofarad · Sep 2, 2013

You never flush the buffer, or close the BufferedWriter.

After the for loop, make the following calls:

buff.flush();
buff.close();

Even with other resources, closing them when done is a good idea.