1

I am a beginner. I have a text file which already has data and the data can be updated but now i would like to add more data from another GUI form to be added at the end of the data

Now it look like this

name//add/password//postcode//email//hpNo//Buyer

I want to add one more item at the end of the row

name//add/password//postcode//email//hpNo//Buyer//PAYMENT

My current code creates a new data instead of adding it to the last column:

 String addcash="";

 try
 {
         File file = new File("MyAccount.txt");
         Scanner reader = new Scanner (file); 
         String line = "", oldtext = "", update = "";

         while(reader.hasNextLine())
         {
             line = reader.nextLine();

             String[] text = line.split("//");
             accNameTextField.setText(new User().getusername());

             if (text[0].equals(accNameTextField.getText())){
                  String update2 =  "//" + addcshComboBox.getSelectedItem(); 
                 addcash += accNameTextField.getText() + update2 + System.lineSeparator(); 

             }
             else
             {
                 addcash += line + System.lineSeparator();
             }
         }

         reader.close();

         FileWriter writer = new FileWriter("MyAccount.txt");
         writer.write(addcash);writer.close();
     }
     catch (IOException ioe)
     {
         ioe.printStackTrace();
     }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

0

Here is the explaination:

To tell the FileWriter that you want to append the text and not to override the existing file you need to add a parameter to the FileWriter constructor, here is the code:

FileWriter writer = new FileWriter("MyAccount.txt", true); // Add the "true" parameter!
writer.write(addcash);
writer.close();
aleb2000
  • 452
  • 4
  • 10
  • I tried it does not work and also i need to add the text at the end of my text file which i will pick from a text box – Akash Gill Sep 15 '16 at 18:07
0
  • need the system to know that there is data over there and skip to the next line so i added [text] on this part of the code

if (text[0].equals(accNameTextField.getText())){ String update2 = "//" + text[1] +"//"+ text[2] +"//"+ text[3] +"//"+ text[4] +"//"+ text[5] +"//"+text[6] +"//"+addcshComboBox.getSelectedItem(); addcash += accNameTextField.getText() + update2 + System.lineSeparator();