一、前言
序列化:將對象轉(zhuǎn)換為二進制序列在網(wǎng)絡中傳輸或保存到磁盤
反序列化:從網(wǎng)絡或磁盤中將二進制序列轉(zhuǎn)換為對象
注意:
- 對象必須實現(xiàn)Serializable接口
- 對象的所有屬性都要能序列化(Integer,Byte等都進行了序列化)
1.1 String
1.2 Integer
二、案例
2.1 編寫大象類
public class Elephant implements Serializable {
private String name;
private String age;
private String sex;
public Elephant(String name, String age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
@Override
public String toString() {
return "Elephant{" +
"name='" + name + ''' +
", age='" + age + ''' +
", sex='" + sex + ''' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
2.2 大象測試類
public class ElephantTest {
public static final String PATH = "D:\elephant";
static void write(Elephant elephant){
//創(chuàng)建對象輸出流
try( ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(PATH))) {
//寫入對象
out.writeObject(elephant);
} catch (IOException e) {
e.printStackTrace();
}
}
static Object read(){
//創(chuàng)建對象輸出流
try( ObjectInputStream in = new ObjectInputStream(new FileInputStream(PATH))) {
//寫入對象
return in.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
Elephant elephant7 = new Elephant("小紅象", "18", "男");
write(elephant7);
Elephant elephant1 = (Elephant) read();
System.out.println(elephant1);
System.out.println(elephant7);
System.out.println(elephant1==elephant7);
}
}
三、運行結(jié)果
寫入D盤的對象:
到此這篇關(guān)于Java序列化與反序列化的文章就介紹到這了,更多相關(guān)Java序列化與反序列化內(nèi)容,請搜索W3Cschool以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,也希望大家以后多多支持我們!