-1

Have this method:

enter image description here

That will be called several times.

My objective is at each call it writes after the content that is already on that file, not overwriting anything. How it's done it just writes the content of the last call.

How can I do it?

Thanks in advance.

Tito
  • 298
  • 2
  • 5
  • 20
  • Using a `BufferedWriter` but concatenating the whole text without even using a `StringBuilder`... Ouch... – fabian Nov 25 '15 at 18:01
  • @fabian can u help me or? – Tito Nov 25 '15 at 18:03
  • You can use the `BufferedWriter` to write the data to the file directly (it even has a method that appends the line seperator for you). If you create a string in memory by repeatedly concatenating multiple Strings, it's best to use `StringBuilder`, since that way the program doesn't create a new `String` object every time the `+` operator is applied. – fabian Nov 25 '15 at 18:09
  • @fabian So I just should create a StringBuilder object and append all the nodes and after write that into the BufferedWriter? Can u explain me this quote "... since that way the program doesn't create a new String object every time the + operator is applied ...". Thanks in advance. – Tito Nov 26 '15 at 17:21
  • If you have a `BufferedWriter`, use it to write the data instead of assembling the whole string in main memory. If you need to write different code that doesn't write the string to a `BufferedWriter` but creates a sting in memory, have a look at `StringBuilder`. – fabian Nov 26 '15 at 18:11
  • @fabian Imagina this example. That method is going to be called 2 times. The first time the visitedList will have 5 nodes. And I need to make "build" a line and write it to a file. And then the method is called again. This time with 3 nodes. And I want to write to the same file but in the next line. What's the best way to do it? – Tito Nov 26 '15 at 21:55

1 Answers1

2

call ovverloaded constructor of FileWriter

 FileWriter fw = new FileWriter(file,true);

If you pass true it will append instead of overwrite

Rahman
  • 3,755
  • 3
  • 26
  • 43
  • Thanks a lot man! You've saved me! Vote up the question! – Tito Nov 25 '15 at 17:47
  • But this will append the all content again on the old content of the file. My objetive is "at each method call" in one "program run". But when I run the program again it should overwrite the old content. – Tito Nov 25 '15 at 17:52
  • http://imgur.com/Kgrh2P8 See here. Each paragraph is a method call. So it writes 1 paragraph in the first call and then appends 3 in the next line. But then when I run the program again it appends the new all 4 paragraphs to the "old" paragraphs. And the objective is only to append between method calls not between program runs. Do you Understand me? – Tito Nov 25 '15 at 17:55