trouble with objectInputStream

the problem is that i cannot added anythig to the data storage. i can add one item and then when i try and add another item, i get an end of file error.

i would really appreciate some help cause ive been trying to fix this problem for a while. -- thanks

/* initialize file for customer storage

* create a new customer vector

* if file not found tell user (recover gracefully)

* read customer instance from file and add to vector

* reads objects to selected file

*/

publicstaticvoid initializeFile()

{

// create Vector instance to hold customer reference variables

customers =new Vector();

if(customerFile.exists() && customerFile.length() != 0)

{

try

{

ObjectInputStream in =new ObjectInputStream(new FileInputStream (customerFile));

// read all customer objects in if customer file exists and length

try

{

while(customerFile.exists())

{

customers.addElement(in.readObject());

}

}

catch(Exception ex)

{

//System.err.println("end of file: error 1 " + ex); //end of file

JOptionPane.showMessageDialog(null,"End of File: " + ex,"Alert!",JOptionPane.ERROR_MESSAGE);

}

}

catch (IOException e)

{

//JOptionPane.showMessageDialog(null,"Input/Ouput Error " + e, "Alert!",JOptionPane.ERROR_MESSAGE);

System.err.println ("Input/Output Error: " + e);

}

}

}

[2481 byte] By [rich79a] at [2007-10-3 9:44:56]
# 1
You are reading the file as long as the file exists, so getting an EOF exception is to be expected.
tsitha at 2007-7-15 5:01:30 > top of Java-index,Java Essentials,Java Programming...
# 2
ok, i need to change that so i can read more than one obj into the file...how could i do that?
rich79a at 2007-7-15 5:01:30 > top of Java-index,Java Essentials,Java Programming...
# 3

> ok, i need to change that so i can read more than one

> obj into the file...

>

> how could i do that?

You're not reading an object into the file, you're reading an object from the file (or out of the file, if you prefer).

So assuming you've an unknown number of objects serialized (written) to that file you could do as you are, but don't tell it to keep going so long as the file exists (as that will likely be a much longer time than you want) tell it to stop at EOF, which, IIRC means you need to catch IOException (I don't see where readObject throws EOFException.) Or you could put everything you wish to serialize into a List prior to writing it into the file, then read it back with one readObject call.

Good Luck

Lee

tsitha at 2007-7-15 5:01:30 > top of Java-index,Java Essentials,Java Programming...