0

I am having problem appending data to already existing .txt file. I have created a TextArea using:

@FXML
private TextArea addBox;

Then created a following method in attempt to add input from TextArea(addBox) to my existing .txt file when 'add' button is clicked. The method works, however it overwrites my .txt file. It will delete everything I have in my .txt file and update it when 'add' button is clicked. Is there anyway I can append input I received from TextArea to my .txt file while keeping my old data? Thank you for your time.

{
   @FXML
   private void addButton(ActionEvent event) throws IOException {
   StringBuilder sb = new StringBuilder();
   sb.append(addBox.getText().toString());

   File file = new File("src/javafxapplication2/Data.txt");
   FileWriter w = new FileWriter(file);
   w.write(sb.toString());
   w.close();
}
  • This has nothing to do with JavaFX or FXML and all to do with how to use the FileWriter properly. Please [search more thoroughly](https://www.google.com/search?q=java+add+to+text+file+site:stackoverflow.com) in the future. – Hovercraft Full Of Eels Aug 02 '18 at 13:56
  • Not this constructor: `new FileWriter(file);` but one that takes 2 parameters, the second being a boolean with a value of `true`: `new FileWriter(file, true);` Also you'll rarely ever write directly with a FileWriter and will usually wrap this in something with buffering. – Hovercraft Full Of Eels Aug 02 '18 at 13:58
  • Thank you for your comment. I will search more throughly next time. Can I put TextArea.getText() inside where "the text" goes from the link you gave me? Also, what kind of question would be java fxml related? I am new to java and thought it was fxml related since I created java fxml and controller class. Just curious thank you! – user10171458 Aug 02 '18 at 14:10
  • I have copied the code and replaced out.println("the text"); with out.println(TextArea.getText()); but input I typed won't get added to existing data. Could you help me? – user10171458 Aug 02 '18 at 14:13
  • I posted a better question https://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java Thank you guys. – user10171458 Aug 02 '18 at 16:39
  • Your question above is a multi-part question, something not allowed, and the duplicate answers one part of the problem. The new question is more specific to your new problem, but you still haven't addressed my comment to it. You state that the code causes no errors, but without handling the exception, **you really don't know this to be true**. – Hovercraft Full Of Eels Aug 02 '18 at 16:45

0 Answers0