Java序列化和反序列化

Posted pascal1000

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java序列化和反序列化相关的知识,希望对你有一定的参考价值。

Java序列化和反序列化

模型类:

package com.hollischaung.serialization.SerializableDemos;
import java.io.Serializable;
/**
* Created by hollis on 16/2/17.
* 实现Serializable接口
*/
public class User1 implements Serializable {

private String name;
private int 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 "User{" +
"name=‘" + name + \‘‘ +
", age=" + age +
‘}‘;
}
}



序列化与反序列化
package com.hollischaung.serialization.SerializableDemos;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import java.io.*;
/**
* Created by hollis on 16/2/17.
* SerializableDemo1 结合SerializableDemo2说明 一个类要想被序列化必须实现Serializable接口
*/
public class SerializableDemo1 {

public static void main(String[] args) {
//Initializes The Object
User1 user = new User1();
user.setName("hollis");
user.setAge(23);
System.out.println(user);

//Write Obj to File
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("tempFile"));
oos.writeObject(user);
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(oos);
}

//Read Obj from File
File file = new File("tempFile");
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream(file));
User1 newUser = (User1) ois.readObject();
System.out.println(newUser);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(ois);
try {
FileUtils.forceDelete(file);
} catch (IOException e) {
e.printStackTrace();
}
}

}
}




code: https://github.com/pascal19821003/StudyJava


以上是关于Java序列化和反序列化的主要内容,如果未能解决你的问题,请参考以下文章

java序列化和反序列化

java反序列化引起的内存溢出怎么解决

一文带你全面了解java对象的序列化和反序列化

Java序列化和反序列化——田少嵩

HashMap(key,Object)中的Java Gson序列化和反序列化对象[重复]

Java的序列化和反序列化