I have some simple code I've been playing with to fix my understanding of serialization and I've managed to be able to serialize and deserialize multiple objects to/from a text file but the issue I'm having is trying to deserialize the objects within the file without having to first re-write them. I know the problem is my loop is using a variable from SerializableObject that gets reset to 0 each time I run the program but I can't figure a way to deserialize every object unless I know this number.
|
Code:
|
public class SerializableObject implements Serializable{
private static final long serialVersionUID = 1654834268554L;
static File file = new File("testSerialize.txt");
static FileOutputStream fos;
static ObjectOutputStream oos;
private String name;
private int age;
static int count = 0;
static{
try { fos = new FileOutputStream(file);
} catch (FileNotFoundException e) { System.out.println("File not found exception"); }
try { oos = new ObjectOutputStream(fos);
} catch (IOException e) { System.out.println("object stream error"); }
}
public SerializableObject(String n, int a){
this.name = n;
this.age = a;
count++;
try {
oos.writeObject(this);
System.out.println("Object written");
} catch (IOException e) {
System.out.println("Error writing object");
}
} |
//taken from my SerializeDriver class
|
Code:
|
private static void readObjects() {
SerializableObject obj1 = null;
try {
fis = new FileInputStream(file);
System.out.println("fis");
} catch (FileNotFoundException e) { System.out.println("Error extracting file"); }
try {
ois = new ObjectInputStream(fis);
System.out.println("ois");
} catch (IOException e) { System.out.println("InputStream error"); }
try {
for(int x = 1; x <= SerializableObject.count; x++){
obj1 = (SerializableObject)ois.readObject();
System.out.println(obj1.getName());
}
} catch (EOFException e) { System.out.println("Reached end of file");
} catch (IOException e) { e.printStackTrace();
} catch (ClassNotFoundException e) { e.printStackTrace();
}
} |
now everything works fine and dandy when I uncomment a call to defaultCreateObjects but I get nothing when all I run is the above readObjects method.