Java的序列化(Serializable)
1. 实现Serializable接口的数据类
class Person implements Serializable {
private String name = "Tom";
private int age = 16;
public Person () {
}
public Person(String name ,int age) {
this.name = name;
this.age = age;
}
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 "Person [name=" + name + ", age=" + age + ", getClass()=" + getClass() + ", hashCode()=" + hashCode()
+ ", toString()=" + super.toString() + "]";
}
}
2. 确定文件输出位置
private static String filename = String.format("D:%s99_temp%sseri", File.separator,File.separator);
3. 序列化
private static void serializable (Person person ) {
try {
ObjectOutputStream oOutputStream = new ObjectOutputStream(new FileOutputStream(filename));
oOutputStream.writeObject(person);
oOutputStream.close();
} catch (FileNotFoundException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
} catch (IOException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
}
反序列化,将持有的文件转化为对象
private static void deserializable() {
try {
ObjectInputStream oInputStream = new ObjectInputStream(new FileInputStream(filename));
Person person = (Person) oInputStream.readObject();
System.out.println(person.toString());
oInputStream.close();
} catch (ClassNotFoundException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
} catch (IOException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
}
5. 考试
public static void main(String[] args) {
serializable(new Person());
deserializable();
}
结果:人员【名称=汤姆,年龄=16,getClass()=com.yanheng.serializable.Person类,hashCode()=1607521710,toString()=com.yanheng.serializable.Person@5fd0d5ae】。
6. 总结
No.使用クラス、インターフェース備考1.データクラス継承Serializableシリアライズ3.シリアライズObjectOutputStreamオブジェクトの書き出し3.シリアライズFileOutputStreamファイルの書き出し4.反シリアライズするObjectInputStreamオブジェクトの読み込み4.反シリアライズするFileInputStreamファイルの読み込み
范例代码
(Note: This is the translation of “Sample code” in Chinese)