java中的对象的序列化,以及新的try...catch块学习
对象的序列化和反序列化:
1、对象的序列需要实现java.util.serializable或者是java.io.externalizable接口。
2、serializable只是一个接口,代表着可序列化,并没有定义任何的抽象方法,只能序列化非静态的,以及没有使用transient关键字修饰的属性,使用此接口最好声明一 个“private static final long serialversionuid = 1l;”常量,确保在类的修改等操作之后,也能够反序列化
3、其中externalizable接口继承serializable接口,可以自定义序列化、反序列化的属性(包含静态属性和transient的),此接口多出了两个抽象方法
writeexternal(objectoutput out) throws ioexception :用于自定义需要序列化的属性
writeexternal(objectoutput out) throws ioexception :用于自定义需要反序列化的属性
4、另一个try(){}...catch(){}finally{}...,这种try...catch可以自动关闭资源,省去了手动关闭的麻烦
try(括号中放需要关闭的资源类代码){此括号中放逻辑代码}catch(异常){}finally{}
示例:
package javase.day23;
import java.io.externalizable;
import java.io.fileinputstream;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.objectinput;
import java.io.objectinputstream;
import java.io.objectoutput;
import java.io.objectoutputstream;
public class testexternalizable {
public static void main(string[] args) {
//自1.7之后的另一个try(){}...catch(){}...
try(
fileoutputstream fos = new fileoutputstream("student.obj");
objectoutputstream oos = new objectoutputstream(fos);
fileinputstream fis = new fileinputstream("student.obj");
objectinputstream ois = new objectinputstream(fis);
){
student student = new student("tom");
student.school = "二中";
student.setage(18);
oos.writeobject(student);
student stu = (student) ois.readobject();
system.out.println(stu);
}catch (ioexception e) {
e.printstacktrace();
} catch (classnotfoundexception e) {
e.printstacktrace();
}
}
}
class student implements externalizable{
private transient string name;
public static string school = "一中";
private int age;
public student() {
super();
}
public student(string name) {
super();
this.name = name;
}
public string getname() {
return name;
}
public void setname(string name) {
this.name = name;
}
public int getage() {
return age;
}
public void setage(int age) {
this.age = age;
}
@override
public string tostring() {
return "student [name=" + name + ", age = " + age + ", school = " + school + "]";
}
@override
public void writeexternal(objectoutput out) throws ioexception {
out.writeutf(name);
out.writeutf(school);
}
@override
public void readexternal(objectinput in) throws ioexception, classnotfoundexception {
name = in.readutf();
school = in.readutf();
}
}