954,164 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Storing classes in files

Hello,
I am trying to do something very simple but my dial up connection is making it hard to research so I'd like some help! I'm trying to store instances of classes I created in a file. Something along these lines:

class apple
{
	int flavor;
	String color;
	apple(int a, String b)
	{
		flavor = a;
		color = b;
	}
}

//.....

	apple RedDelicious = new apple(10, "red");
	writeFile.write(RedDelicious);


I know that there is some way to do this through serialization and I've also heard that something along the lines of FileOutputStream/FileInputStream will allow me to write/read the classes but I would appreciate a little guidance on their use in this context. I'm sorry to bother you guys but my dial up is hindering the research process! Thanks!

dmanw100
Posting Whiz in Training
242 posts since Apr 2008
Reputation Points: 104
Solved Threads: 27
 

Your class must implements a java.io.Serializable Interface and one more thing is that you have to use java.io.ObjectInputStream and java.io.ObjectOutputStream class to read and write objects respectively.

class apple implements java.io.Serializable
{
	int flavor;
	String color;
	apple(int a, String b)
	{
		flavor = a;
		color = b;
	}
}

//.....
               
	apple RedDelicious = new apple(10, "red");
                java.io.ObjectOutputStream os=new java.io.ObjectOutputStream(new java.io.FileOutputStream("data.txt"));

	os.writeObject(RedDelicious);
                os.flush();
__avd
Posting Genius (adatapost)
Moderator
8,647 posts since Oct 2008
Reputation Points: 2,136
Solved Threads: 1,241
 

Thanks for reminding me. It's been awhile since I tried it and one can only research on dial up can only go so long until the patience runs out ha!

dmanw100
Posting Whiz in Training
242 posts since Apr 2008
Reputation Points: 104
Solved Threads: 27
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You