ive got a problem with deserializing at the beginning of the program.
public static void main(String[] args) throws IOException, ClassNotFoundException{
Test object = new Test(); // Test implements Serializable
//start
deserialize();
//do something
//end
serialize(object);
}
public static void deserialize()
{
test object = null;
try
{
FileInputStream file= new FileInputStream(".../Example.ser");
if(file.read()!=-1) //the first time the file will be empty
{
ObjectInputStream read= new ObjectInputStream(file); //here an exception is thrown the second time the program is started
object = (Test) read.readObject();
object .printdata();
read.close();
file.close();
}
else
{
file.close();
}
}catch(IOException i)
{
i.printStackTrace();
return;
}catch(ClassNotFoundException c)
{
c.printStackTrace();
return;
}
}
public static void serialize(Test object)
{
try
{
FileOutputStream file =
new FileOutputStream(".../Example.ser");
ObjectOutputStream write = new ObjectOutputStream(file );
write .writeObject(object);
write .close();
file .close();
}catch(IOException i)
{
i.printStackTrace();
}
}
the program works if would switch serialize and deserialize or if i call deserialize after serialize. it runs fine the first time but if i start it a second time deserialize @ ObjectInputStream read= new ObjectInputStream(file); throws an streamcorrupted exception.
at program start the serialize file has to be deserialized and printed and as i said if switch the calls and then copy the call of deserialize back to the top it works but not if it stays like that. the first time it runs but the second time the exception is thrown.
FileOutputStream file = new FileOutputStream(".../Example.ser",false);when you serialize to empty the file.FileNotFoundExceptionif the file doesn't exist. You can't get any kind a stream whether corrupt or otherwise from a non-existent file.new FileOutputStream(String)is equivalent tonew FileOutputStream(String, boolean)when the second parameter is false.