• Post Reply Bookmark Topic Watch Topic
  • New Topic

Writing data to a file using PrintWriter  RSS feed

 
Dan Pants
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am creating a car simulator that simulators the odometer and fuel gauge on a car. I want to print the results to a text file but it seems to be printing only the last two lines instead of all of them. How can I make it so it doesn't overwrite the previous input? What am I missing?

Any help or advice is appreciated. Thank you!

Here's my main method:

 
Dan Pants
Greenhorn
Posts: 13
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving the PrintWriter writer = new PrintWriter("mileage.txt"); before the while loop, and closing it after fixed the issue!
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dan Pants wrote:Moving the PrintWriter writer = new PrintWriter("mileage.txt"); before the while loop, and closing it after fixed the issue!

Thanks for adding that Dan. The only thing I would suggest is that you take as much code out of your main() method as you can and put it somewhere else - either another static method or (probably even better) an instance one. You might want to read the MainIsAPain page for more details.

Winston
 
Tony Docherty
Bartender
Posts: 3271
82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And Welcome to the Ranch
 
Dan Pants
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the advice guys, much appreciated!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!