0

I've been banging my head against the wall last couple of hours trying to get my program to work, but to no success.

I'm working on a simple JFrame based program that should open the window, let me input the variables and then if I press Save, save them to selected .csv file.

The problem however arises when I try to save 2 or more sets of variables, the first one always gets overwritten and only new one is there.

For example instead of:

Mark, 100, 2, John, 50, 1

In the file I only find

John 50, 1

I'm guessing it has to do with new bufferedwriter being created every time I click 'Save' button but I have no idea how to get around doing that, I tried multiple positions of placing it but it never works because I get error if it's outside the Action method.

Here's the code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

/**
 * Demonstrates etc
 */
public class Homework1 extends JFrame implements ActionListener {

   JTextField jtfName1;
   JTextField jtfName2;
   JTextField jtfName3;
   JTextField jtfName4;

   static File file = new File("121Lab1.csv"); 

   public Homework1() {
        // Set BorderLayout with horizontal gap 5 and vertical gap 10
      setLayout(new BorderLayout(10, 10));


        // Create a JPanel with FlowLayout for the South of the JFrame's BorderLayout

      JPanel jpSouth = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 3));

        // Create some buttons to place in the south area
      JButton jbCalc = new JButton("Calculate");
      JButton jbSave = new JButton("Save");
      JButton jbClear = new JButton("Clear");
      JButton jbExit = new JButton("Exit");

      jpSouth.add(jbCalc);
      jpSouth.add(jbSave);
      jpSouth.add(jbClear);
      jpSouth.add(jbExit);

      jbCalc.addActionListener(this);
      jbSave.addActionListener(this);
      jbClear.addActionListener(this);
      jbExit.addActionListener(this);


        // Place the south panel in the JFrame's south area
      add(jpSouth, BorderLayout.SOUTH);

        // Add textfields to the rest of the frame

      JPanel jpCenter = new JPanel(new GridLayout(0,2));

      jpCenter.add(new JLabel("Item name: ", SwingConstants.RIGHT));
      jtfName1 = new JTextField("", 10);
      jpCenter.add(jtfName1);
      jtfName1.addActionListener(this);

      jpCenter.add(new JLabel("Number of: ", SwingConstants.RIGHT));
      jtfName2 = new JTextField("", 10);
      jpCenter.add(jtfName2);
      jtfName2.addActionListener(this);

      jpCenter.add(new JLabel("Cost: ", SwingConstants.RIGHT));
      jtfName3 = new JTextField("", 10);
      jpCenter.add(jtfName3);
      jtfName3.addActionListener(this);

      jpCenter.add(new JLabel("Amount owed: ", SwingConstants.RIGHT));
      jtfName4 = new JTextField("", 10);
      jpCenter.add(jtfName4);
      jtfName4.addActionListener(this);

      add(jpCenter, BorderLayout.CENTER);

   }

   public void actionPerformed(ActionEvent ae) {
      String actionString = ae.getActionCommand(); // gets the string on the component
      Object actionObj = ae.getSource();


      if (actionString.equalsIgnoreCase("Calculate")) { // ae.getSource() == jbCancel
         System.out.println("You clicked Calculate");
         try {
            double value = Double.parseDouble(jtfName2.getText())*Double.parseDouble(jtfName3.getText());
            jtfName4.setText(String.format("%.2f", value));
         } 
         catch (NumberFormatException nfe) {
            jtfName4.setText("Not a number");
         }

      } 
      else if (actionString.equalsIgnoreCase("Save")) { 

         try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(file));
            writer.write(jtfName1.getText()+",");
            writer.write(jtfName2.getText()+",");
            writer.write(jtfName3.getText()+"\r\n");
            writer.flush();
            writer.close();
         } 
         catch(IOException e) {
            System.out.println("IO Error");
         }         
      } 
      else if (actionString.equalsIgnoreCase("Clear")) { 

         System.out.println("You clicked Clear");
         jtfName1.setText("");
         jtfName2.setText("");
         jtfName3.setText("");
         jtfName4.setText("");

      } 
      else if (actionString.equalsIgnoreCase("Exit")) { 


         setVisible(false);
         dispose();


      } 
      else {
         System.out.println("Unknown command: " + actionString);
         System.out.println("Unknown source:  " + actionObj);
      }
   } 




   public static void main(String[] args) throws IOException {

      Homework1 jfMain = new Homework1();
      jfMain.setTitle("Item Order Calculator");
      jfMain.setSize(450, 200);
      jfMain.setLocationRelativeTo(null);       // Center JFrame
      jfMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      jfMain.setVisible(true);


   } // end main
} // end class JPanelTester
user2627736
  • 281
  • 1
  • 4
  • 13

3 Answers3

1

Each time you click save, the file and it's contents are been overwritten. You need to tell the FileWriter that you wish to append to the end of the file, for example...

BufferedWriter writer = new BufferedWriter(new FileWriter(file), true);

See FileWriter(File, boolean) for more details

BufferedWriter also has a newLine method, which can write a new line to the file...

writer.write(jtfName1.getText()+",");
writer.write(jtfName2.getText()+",");
writer.write(jtfName3.getText());
writer.newLine();

You're also not managing your resources very well. If you open a resource, you should make every attempt to close it, otherwise you could end up with leaking resources and other strange problems

Luckily in Java 7+, it's very easy to manage these types of resources

    try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
        writer.write(jtfName1.getText()+",");
        writer.write(jtfName2.getText()+",");
        writer.write(jtfName3.getText());
        writer.newLine();
     } 
     catch(IOException e) {
        System.out.println("IO Error");
     }       

See The try-with-resources Statement for more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

You could clear/delete the file on startup and append to the file like that: How to append text to an existing file in Java

Community
  • 1
  • 1
slartidan
  • 20,403
  • 15
  • 83
  • 131
0

i will suggest you one other writer(i have worked on this):

try{ 

 PrintWriter Writer = new PrintWriter(new File("path of file/file.(whatever)");

    //example
        writer.write(jtfName1.getText()+",");
        writer.printf("  "); //Leave some space
        writer.write(jtfName2.getText()+",");
        writer.printf("  "); //Leave some space
        writer.write(jtfName3.getText()+"\r\n");
        writer.printf("  "); //Leave some space

        writer.flush();
        writer.close();

} catch (FileNotFoundException e) { e.printStackTrace(); }

if you want to leave some space or write something use:writer.printf(".");

if you want to leave a line use writer.println();

Of course it has and other fuctions to use with this writer..

Let me know if it does your job.....

crAlexander
  • 376
  • 1
  • 2
  • 12
  • There's nothing wrong with the using the `Writer` and, as far as your example goes, the `PrintWriter` doesn't really add any functionality that the OP doesn't already have (if you were formatting the `String`s in some way, that might be different). This will still only write the last content that the OP writes the file, overwriting the content... – MadProgrammer Jan 29 '15 at 21:12
  • for the save that the question need it does the job,i use it to save data into a program i am making..(it add the content one after other it can also append) he/she can tranform it to do this.Ok i know BufferReader is one nice option but i haven't worked with this too much that's why i am suggestion this.. – crAlexander Jan 29 '15 at 21:16
  • Same here, I tend to use the `Writer`s over `PrintWriter` personally, if you could say that it supported better character encoding or something, then that would be fine, but simply saying "you should use this because I do" isn't really a good reason for the OP to change - IMHO. – MadProgrammer Jan 29 '15 at 21:45
  • Also, you're example still isn't going to solve the issue of only the last element been written (the file been truncated), from the Java Docs *"`PrintWriter(File)` - The file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered"* – MadProgrammer Jan 29 '15 at 21:45
  • hm the user want after saving to that file to append again .... ok here is a little problem with that writer yes..(i only used it to save one time and then close the file yes yes it overrides... thats true..) – crAlexander Jan 30 '15 at 14:29