简体   繁体   中英

How to add information to existing text file in java

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();
     }
}

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();
  • 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM