说起序列化,可能大部分人在实际工作中都没有使用过,虽然没用过,但不表示它不重要,那什么是JAVA序列化呢?
JAVA序列化也可称为对象序列化机制:允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。序列化的好处在于可将任何实现了Serializable接口的对象转化为字节数据,使其在保存和传输时可被还原。序列化是 RMI(Remote Method Invoke – 远程方法调用)过程的参数和返回值都必须实现的机制,而 RMI 是 JavaEE 的基础。因此序列化机制是JavaEE 平台的基础。
说完理论的东西,我们现在来实际操作一下,看看是怎么通过代码来实现对象序列化的:
先创建一个JAVA类:
public class TestBean implements Serializable{
public static final long serialVersionUID = 475463534532L;
private String name;
private int age;
private int id;
private Dog dog;
public TestBean(String name, int age, int id) {
this.name = name;
this.age = age;
this.id = id;
}
public TestBean(String name, int age, int id, Dog dog) {
this.name = name;
this.age = age;
this.id = id;
this.dog = dog;
}
@Override
public String toString() {
return "TestBean{" +
"name='" + name + '\'' +
", age=" + age +
", id=" + id +
", dog=" + dog +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
public TestBean(String name, int age) {
this.name = name;
this.age = age;
}
public TestBean() {
}
}
class Dog implements Serializable{
public static final long serialVersionUID = 4754534532L;
private String dogName;
@Override
public String toString() {
return "Dog{" +
"dogName=" + dogName +
'}';
}
public String getDogName() {
return dogName;
}
public void setDogName(String dogName) {
this.dogName = dogName;
}
public Dog(String dogName) {
this.dogName = dogName;
}
}
再来一个测试类:
public class SerializableTest {
@Test
public void testObjectOutputStream(){
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("object.data"));
oos.writeObject(new String("重庆加油"));
oos.flush();//刷新操作
oos.writeObject(new TestBean("哈哈哈",15));
oos.flush();
oos.writeObject(new TestBean("意呆利",44,5000,new Dog("旺财")));
oos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(oos != null){
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void testObjectInputStream(){
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("object.data"));
Object obj = ois.readObject();
String str = (String) obj;
TestBean p = (TestBean) ois.readObject();
TestBean p1 = (TestBean) ois.readObject();
System.out.println(str);
System.out.println(p);
System.out.println(p1);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if(ois != null){
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
小伙伴,虽然不常用,但还是需要了解它的用法和用途哦。
欢迎大家入群交流,虫洞栈公众号的作者坐阵本群,有机会与大神面对面,赶紧来哦