• Post Reply Bookmark Topic Watch Topic
  • New Topic

writing to textfile without overwriting contents  RSS feed

 
Christoph Czon
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all!

I have the following problem: I wrote a small game. Now I want to print the winner and his scores to a text file called "highscore.bla".
However, I dont want to overwrite existing lines in the file. Unfortunately the following code does overwrite the file.



Where is my mistake?
Id appreciate your help! Thank you!
 
Christoph Czon
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
solved... you can close it
 
Rob Spoor
Sheriff
Posts: 21048
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We don't close threads just because they have been answered.

How did you solve it? By using one of the other FileWriter constructors?
 
sujay bawaskar
Greenhorn
Posts: 7
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
change
03. PrintWriter out = new PrintWriter(new FileWriter(highscore));

to

PrintWriter out = new PrintWriter(new FileWriter(highscore,true));
 
Christoph Czon
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your answers!

It's good to hear btw that threads don't get closed just because they were solved... I'm still used to not so user friendly forums I guess ;)

Well I solved it using the Scanner class.

I'm sorry I didnt watch the thread more closely and now time has passed, I have edited the method a lot since then. But the basics are still the same. It prints the highscores to the highscore file and doesnt overwrite existing lines in the file. Except for some design issues, this is what I wanted.

Here is the new method now:



The key to success was the scan.hasNextLine() method i guess.
Still there must be more elegant ways to solve this.. like avoiding the very similar code in line 16 and 18. I will get back to it soon I hope.

Also I will try out your suggestion using the old version of the method, sujay.
 
Rob Spoor
Sheriff
Posts: 21048
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try using a StringBuilder (or StringBuffer in Java 1.4) instead of this form of string concatenation.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!