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!

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();

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!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.