随笔- 62  文章- 1  评论- 5  阅读- 13004 

刚好接触到要用的思路,扩充下

1 对象序列化

1.1 对象要序列化要实现Serializable接口

1.2 然后通过ObjectInputStream 对象读入流来读入一个对象

new ObjectOutputStream(new xxOutputStream(""))
new的时候传入一个读入流

1.3 需要申明一个序列化版本号

private static final long serialVersionUID = ;
//用于协商该类的版本,序列化和反序列的版本号不一致时,会异常。修订后应该修改版本号,这样之前序列化的对象进行反序列的时候会失败,抛异常。
//序列化对象
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(""));
//写入
oos.writeObject();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(""));
//读进
Object o = ois.readObject();

1.4 序列化对象——文件

public class Main {
public static void main(String[] args) throws ClassNotFoundException {
Vector<Integer> list1 = new Vector<>();
list1.add(2);
try {
FileOutputStream fileOutputStream = new FileOutputStream("data.txt");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(list1);
objectOutputStream.flush();
FileInputStream fileInputStream = new FileInputStream("data.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Object o = objectInputStream.readObject();
List<Integer> list2 = (List<Integer>) o;
System.out.println(list2.get(0));
} catch (IOException e) {
e.printStackTrace();
}
}
}

1.5序列化对象——字节

public class Main {
public static void main(String[] args) throws ClassNotFoundException {
Vector<Integer> list1 = new Vector<>();
list1.add(2);
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(list1);
objectOutputStream.flush();
// String s = objectOutputStream.toString();
byte[] bytes = byteArrayOutputStream.toByteArray();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
Object o = objectInputStream.readObject();
List<Integer> list2 = (List<Integer>) o;
System.out.println(list2.get(0));
} catch (IOException e) {
e.printStackTrace();
}
}
}
 posted on     阅读(62)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示

目录导航