aspose file tools*
The moose likes I/O and Streams and the fly likes Write objects to a File Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Write objects to a File" Watch "Write objects to a File" New topic
Author

Write objects to a File

Mat Spiffy
Greenhorn

Joined: Oct 31, 2008
Posts: 7
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
internet detective
Marshal

Joined: May 26, 2003
Posts: 30537
    
150

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.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Mat Spiffy
Greenhorn

Joined: Oct 31, 2008
Posts: 7
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

Joined: Aug 05, 2005
Posts: 3568
    
  15
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.


Joanne
Mat Spiffy
Greenhorn

Joined: Oct 31, 2008
Posts: 7
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

Joined: Oct 27, 2005
Posts: 19697
    
  20

Change to the other constructor.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Mat Spiffy
Greenhorn

Joined: Oct 31, 2008
Posts: 7
Thanks Joanne and Rob

Changing the constructor of FileWriter did the trick.

Thanks a lot for your guidance.

Best Regards
 
Don't get me started about those stupid light bulbs.
 
subject: Write objects to a File