Reading serialised object from file
Posted
by nico
on Stack Overflow
See other posts from Stack Overflow
or by nico
Published on 2010-05-26T13:50:25Z
Indexed on
2010/05/26
14:11 UTC
Read the original article
Hit count: 261
java
|serialization
Hi everyone. I'm writing a little Java program (it's an ImageJ plugin, but the problem is not specifically ImageJ related) and I have some problem, most probably due to the fact that I never really programmed in Java before...
So, I have a Vector of Vectors and I'm trying to save it to a file and read it.
The variable is defined as:
Vector <Vector <myROI> > ROIs = new Vector <Vector <myROI> >();
where myROI
is a class that I previously defined.
Now, to write the vector to a file I use:
void saveROIs()
{
SaveDialog save = new SaveDialog("Save ROIs...", imp.getTitle(), ".xroi");
String name = save.getFileName();
if (name == null)
return;
String dir = save.getDirectory();
try
{
FileOutputStream fos = new FileOutputStream(dir+name);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(ROIs);
oos.close();
}
catch (Exception e)
{
IJ.log(e.toString());
}
}
This correctly generates a binary file containing (I suppose) the object ROIs
.
Now, I use a very similar code to read the file:
void loadROIs()
{
OpenDialog open = new OpenDialog("Load ROIs...", imp.getTitle(), ".xroi");
String name = open.getFileName();
if (name == null)
return;
String dir = open.getDirectory();
try
{
FileInputStream fin = new FileInputStream(dir+name);
ObjectInputStream ois = new ObjectInputStream(fin);
ROIs = (Vector <Vector <myROI> >) ois.readObject(); // This gives error
ois.close();
}
catch (Exception e)
{
IJ.log(e.toString());
}
}
But this function does not work.
First, I get a warning:
warning: [unchecked] unchecked cast found : java.lang.Object
required: java.util.Vector<java.util.Vector<myROI>>
ROIs = (Vector <Vector <myROI> >) ois.readObject();
^
I Googled for that and see that I can suppress by prepending @SuppressWarnings("unchecked")
, but this just makes things worst, as I get an error:
<identifier> expected
ROIs = (Vector <Vector <myROI> >) ois.readObject();
^
In any case, if I omit @SuppressWarnings
and ignore the warning, the object is not read and an exception is thrown
java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: myROI
Again Google tells me myROI
needs to implements Serializable
. I tried just adding implements Serializable
to the class definition, but it is not sufficient. Can anyone give me some hints on how to procede in this case? Also, how to get rid of the typecast warning?
© Stack Overflow or respective owner