Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Write objects to a File

 
Mat Spiffy
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I have a class Person that has name, country and dob attributes. Assume there are 5 such objects.
I am sorting them by their dob. I can print the 5 objects (sorted by their dob) on the console. Now I want to write the output to a txt file. I tried using BufferedWriter and FileWriter. But only the fifth object gets written into the file. In other words, the objects get over written on the file.

Can some one give me code snippet or guidance as to how can I solve this problem of writing objects into a file.

Thanks
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34422
347
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mat,
Welcome to JavaRanch!

Are you using the constructor for FileWriter that takes two parameters? The first is the file. The second is a boolean for whether you want to append or overwrite the contents.
 
Mat Spiffy
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jeanne,

Thanks for your reply.

Here is the method that I am using to write to a file.




Here is a snippet of my main(). I am getting the Strings in the for loop and trying to write those strings into a text file. pfinal is an array of type Person.




pfinal has 5 objects each having lastname, firstname, gender, dob and favcolor attributes. When I write to the file, only the last(pfinal[4]) object gets written on the file.

I want to write all the five objects in five lines on output.txt.

Please advice.

Thanks
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jeanne Boyarsky:
Are you using the constructor for FileWriter that takes two parameters? The first is the file. The second is a boolean for whether you want to append or overwrite the contents.
 
Mat Spiffy
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Joanne,

I am using the FileWriter that takes one argument i.e. the file name.

Can you suggest me what changes should I make in the code?

Thanks
 
Rob Spoor
Sheriff
Pie
Posts: 20532
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Change to the other constructor.
 
Mat Spiffy
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Joanne and Rob

Changing the constructor of FileWriter did the trick.

Thanks a lot for your guidance.

Best Regards
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic