Sander_Blaadjes
Sander_Blaadjes

Reputation: 159

Don't create a new CSV file each time

So I am trying to make something for my work but each time I use this method (Which I found on the Internet) It creates a new CSV file, but I want to add the data each time, without removing what was previously there.

            public static void generateCsvFile(String sFileName) {
            try {
                NummerS = Nummer.getText();
                LocatiesS = Locatie.getText();
                LoginS = Login.getText();
                Nummer5S = Nummer5.getText();
                Nummer1S = Nummer1.getText();
                DatumS = Datum.getText();


                FileWriter writer = new FileWriter(sFileName);
                writer.append(NummerS);
                writer.append(';');
                writer.append(LocatiesS);
                writer.append(';');
                writer.append(LoginS);
                writer.append(';');
                writer.append(DatumS);
                writer.append(';');
                writer.append(Nummer1S);
                writer.append(';');
                writer.append(Nummer5S);
                writer.append(';');
                if(listt.getSelectedValue() != null)
                {
                writer.append(listt.getSelectedValue().toString());
                }
                Workbook workbook = null;
                try {
                    workbook = Workbook.getWorkbook(new File("F:\\test.xls"));
                } catch (BiffException e1) {

                    e1.printStackTrace();
                } catch (IOException e1) {

                    e1.printStackTrace();
                }

                writer.append(';');
                Sheet sheet = workbook.getSheet(0);
                for(Cell c : sheet.getColumn(1)){
                    if(listt.getSelectedValue() != null)
                    {
                      if(c.getContents().contains(listt.getSelectedValue().toString())){

                         System.out.println(c.getColumn() + " , " + c.getRow());
                         writer.append(sheet.getCell(c.getColumn()+1,c.getRow()).getContents());
                      } else {

                      }
                }
                }
                // generate whatever data you want
                writer.append("\n");
                writer.flush();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

and this is where I call the method.

if(e.getSource().equals(save)){
    generateCsvFile("f:\\testss.csv");
    JOptionPane.showMessageDialog(null, "Saved!");
}

Upvotes: 0

Views: 84

Answers (1)

Michal
Michal

Reputation: 15669

You are calling the wrong constructor while creating the FileWriter. Rewrite it to:

new FileWriter(sFileName, true);

That should preserve your data. Here is a direct link to the documentation.

Upvotes: 1

Related Questions