import org.junit.Test;
import java.io.*;
/**
* @author
* @date 2021/4/2 14:46
* 对象的序列化
*1.类对象必须实现Serializable接口才可以被序列化
*2.并要补充一个序列版本号,随便写
* public static final long serialVersionUID=....L;
*/
public class ObjectOutputStream {
@Test
public void test1() {
java.io.ObjectOutputStream obj= null;
try {
File file=new File("object");
FileOutputStream fs=new FileOutputStream(file);
obj = new java.io.ObjectOutputStream(fs);
obj.writeObject(new String("helloworld"));
obj.writeObject(new User("小明",18));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (obj!=null){
try {
obj.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void test2(){
ObjectInputStream oi= null;
User user= null;
String s=null;
try {
File file=new File("object");
FileInputStream fi=new FileInputStream(file);
oi = new ObjectInputStream(fi);
s=(String)oi.readObject();
user = (User)oi.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (oi!=null){
try {
oi.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println(s);
System.out.println(user);
}
}
ObjectOutputStream对象序列化
最新推荐文章于 2023-08-31 20:33:42 发布