是jym
是这样的,对象序列化之后,不管是什么文件后缀,打开都是乱码。反序列化后,取出来的数据用打印toString就是正常的。
不需要
调用啦就要关闭 从小到大关闭
通过反射会去调用你所要序列化的对象是否有对应名称的方法,来决定是否采用默认的
特殊的方法签名,我已经明白了
序列化后以字节形式写入硬盘中,由于实现了序列化接口,所以jvm会执行序列化
EOFException
文件尾异常
很明显,你用readInt无法读出Int,反而读到了文件尾
那是因为你没有在类中创建toString()函数
public String toString() {
return id+" "+name+" "+age;
}
方法括号里有 java.io.ObjectOutputStream s
ObjectOutputStream的实例调用writeObject(obj)方法时,虚拟机通过反射检查对象的类是否实现Serializable接口,如果实现,则虚拟机内部进行序列化操作,同时通过反射检测类是否有writeObject方法,如果有则调用obj的writeObject方法,反序列化类似。我是这样理解的,欢迎指正。
这样写是出于兼容性考虑。
旧版本的JDK中,ArrayList的实现有所不同,会对length字段进行序列化。
而新版的JDK中,对优化了ArrayList的实现,不再序列化length字段。
这个时候,如果去掉s.writeInt(size),那么新版本JDK序列化的对象,在旧版本中就无法正确读取,
因为缺少了length字段。
因此这种写法看起来多此一举,实际上却保证了兼容性。
附上官方解释:defaultReadObject() and defaultWriteObject() should be the first method call inside readObject(ObjectInputStream o) and writeObject(ObjectOutputStream o). It reads and writes all the non-transient fields of the class respectively.
These methods also helps in backward and future compatibility. If in future you add some non-transient field to the class and you are trying to deserialize it by the older version of class then the defaultReadObject() method will neglect the newly added field, similarly if you deserialize the old serialized object by the new version then the new non transient field will take default value from JVM i.e. if its object then null else if primitive then boolean to false, int to 0 etc….
private void writeObject(java.io.ObjectOutputStream s)throws java.io.IOException{
s.defaultWriteObject();//把虚拟机默认能序列化的元素 进行序列化
s.writeUTF(str);
}
private void readObject(java.io.ObjectInputStream s)throws java.io.IOException,ClassNotFoundException{
s.defaultReadObject();//将默认能反序列化元素 反序列化
this.str= s.readUTF();
}
//我是看提示 试验的,成果了,可能误打误撞吧;
不是的,默认的是将有效的和无效的全部都序列化了。
重写的writeObject要写在Student类中
当调用到writeObject方法时,会直接调用本类的writeObject方法。
在本类的writeObject方法中使用s.defaultWriteObject();调用java提供的写入对象的方法。
在这句代码之后执行自己的代码
输入ArrayLIist,按住Ctrl,用鼠标就能点出来,要关联源码
WriteObject和ReadObject方法写错了,首字母应该小写
不求甚解即可
点击String 按 F3
Ctrl+f 就能查找
不懂的看一下源码和API解释,一目了然!!学JAVA就是要学会看文档和源码~~~~这才是最好的学习方法!
解决了吗???
只是个例子而已啊。
明白了,oos才是writeObject的参数,弄混了。。。
ctrl+f
说明你没有导入源码文件,在你的JDK安装目录下有个src.zip文件。将它导入进去即可,如果没有的话。你可以到http://download.csdn.net/detail/michael_hm/9587153 这里下载源码,这是我1.8的源码。放到JDK目录下,导进去就可以,怎么导进去,网上有相关的教材。我就不截图了
可以一起操作,这样方便显示