Hello all. I'm trying to read/write objects to a file using streams.
Basically I have a table that contains up to 10 objects. Each object contains several pieces of data such as a name and adress etc
both my class and the object's class are implementing java.io.Serializable
here's the top of my object's class
and here are my filewriter and filereader functions in my other class that creates a table[10] and adds 10 occupants to it
and here's my problem. When I write to the file.. If I look at the file's contents afterwards it shows that it only wrote the first piece of data for each object. In this case only the name but not the adress.
And if I try to load that back into a table of objects well that just plain don't work.. I'm obviously missing something pretty important.. but I've been reading on serialization and I tried a couple of things but still haven't found what I'm doing so wrong.
I'd really appreciate if someone could point out to me the proper way of doing what I want to do which is writing and reading objects with complex structures that contain lots of data
thanks a lot!
Basically I have a table that contains up to 10 objects. Each object contains several pieces of data such as a name and adress etc
both my class and the object's class are implementing java.io.Serializable
here's the top of my object's class
Code:
public class Occupant implements java.io.Serializable
{
String occupantName, adress;
public Occupant( String n, String a )
{
this.playerName = n;
this.adress = a;
}
and here are my filewriter and filereader functions in my other class that creates a table[10] and adds 10 occupants to it
Code:
public void writeFile()
{
try
{
FileOutputStream out = new FileOutputStream("datafile.data");
ObjectOutputStream oos = new ObjectOutputStream(out);
for (int i = 0 ; i < 10; i++)
{
oos.writeObject ( Occupants[i] );
}
oos.flush();
}
catch (Exception e)
{
System.out.println("Problem serializing: " + e);
}
}
public void readFile()
{
try
{
FileInputStream in = new FileInputStream("datafile.data");
ObjectInputStream ois = new ObjectInputStream(in);
Occupant Occupants = (Occupant)ois.readObject();
}
catch (Exception e)
{
System.out.println("Problem serializing: " + e);
}
}
and here's my problem. When I write to the file.. If I look at the file's contents afterwards it shows that it only wrote the first piece of data for each object. In this case only the name but not the adress.
And if I try to load that back into a table of objects well that just plain don't work.. I'm obviously missing something pretty important.. but I've been reading on serialization and I tried a couple of things but still haven't found what I'm doing so wrong.
I'd really appreciate if someone could point out to me the proper way of doing what I want to do which is writing and reading objects with complex structures that contain lots of data
thanks a lot!