在做序列化时,我发现在解序列化过程中,当文件被读取直到在while循环中使用readObject()
然后EOFException
。在java中定制序列化过程
所以我想出了这个解决方案,创建了一个实现Serializable接口的类EofIndicatorClass
。在序列化期间写入EofIndicatorClass
的实例EOF
以在序列化过程期间指示EOF
。
在序列化过程中,如果oin.readObject()
返回instanceof EofIndicatorClass
那意味着它是EOF
,则退出while循环并且不会抛出EOFException
。
所以下面就是基于这种办法现在请告知程序是这样的apprach是正确的或有任何其他更好的方法存在
/*
* Class whose instance will be written at EOF during serialization
* to indicate EOF during deSerialization process.
*/
class EofIndicatorClass implements Serializable{}
其他类
class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
public Employee(String name) {
this.name = name;
}
@Override
public String toString() {
return "Employee [name=" + name + "]";
}
}
现在系列化发生
public class SerializeEmployee {
public static void main(String[] args) {
Employee object1 = new Employee("amy");
Employee object2 = new Employee("ankit");
try {
OutputStream fout = new FileOutputStream("ser.txt");
ObjectOutput oout = new ObjectOutputStream(fout);
System.out.println("Serialization process has started, "
+ "serializing employee objects...");
oout.writeObject(object1);
oout.writeObject(object2);
//write instance of EofIndicatorClass at EOF
oout.writeObject(new EofIndicatorClass());
oout.close();
System.out.println("Object Serialization completed.");
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
现在发生钝化
public class DeSerializeEmployee {
public static void main(String[] args) {
InputStream fin;
try {
fin = new FileInputStream("ser.txt");
ObjectInput oin = new ObjectInputStream(fin);
System.out.println("DeSerialization process has started, "
+ "displaying employee objects...");
/*
*If oin.readObject() returns instanceof EofIndicatorClass that means
*it's EOF, exit while loop and EOFException will not be thrown.
*/
Object obj;
while(!((obj = oin.readObject()) instanceof EofIndicatorClass)){
System.out.println(obj);
}
oin.close();
} catch (EOFException e) {
System.out.println("File ended");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("Object DeSerialization completed.");
}
}
为什么不使用Externalizable接口。 Externalizable的基本用途是定制序列化过程。 https://www.tuturself.com/posts/view?menuId=58&postId=393 –
@ArpanDas用它来解决流'问题'的末端*如何?* – EJP