Tom
Tom

Reputation: 89

When writing to a CSV file, previous string is overwritten

I am trying to make a simple program that saves user input on a swing form to a .CSV file. I have it working to where it will write the first time.

If I exit out or enter a second set of values, and click save the previous string is overwritten in the file.

            try {
                PrintWriter pw = new PrintWriter(new File("customer.csv"));
                StringBuilder sb = new StringBuilder();

                sb.append(merch);
                sb.append(',');
                sb.append(cont);
                sb.append(',');
                sb.append(mail);
                sb.append(',');
                sb.append(cphone);
                sb.append('\n');

                pw.write(sb.toString());
                pw.flush();
                pw.close();

            } catch (FileNotFoundException e1) {
                JOptionPane.showMessageDialog(frame, "File Not     Located");
                e1.printStackTrace();

I tried adding the 'sb.append('\n');' to the end thinking that would fix it, but it did not.

Upvotes: 0

Views: 593

Answers (3)

Dave L.
Dave L.

Reputation: 9781

If you're using Java 8, you might want to clean it up like so:

    try(Writer pw = new PrintWriter(new BufferedWriter(new FileWriter("customer.csv", true)))) {
        pw.write(new StringJoiner(",", "", "\n")
            .add(merch)
            .add(cont)
            .add(mail)
            .add(cphone)
            .toString()
        );
    } catch (IOException e1) {
        JOptionPane.showMessageDialog(frame, "File Not Located");
        e1.printStackTrace();
    }

Upvotes: 0

Factory Girl
Factory Girl

Reputation: 897

PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("file.txt", true)));

Upvotes: 0

hoaz
hoaz

Reputation: 10143

You need to open file in append mode:

PrintWriter pw = new PrintWriter(new FileWriter("customer.csv", true));

Upvotes: 3

Related Questions